将Unix时间戳转换为Date、Json属性动态生成反序列化、序列化指定属性

时间:2021-04-17 21:06:12

实体类

public class Test
{
[JsonIgnore]
public string GetDate
{
get
{
return GetTime.ToString("yyyy-MM-dd");
}
}
[JsonProperty(PropertyName = "get")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime GetTime { get; set; } [JsonProperty(PropertyName = "ns")]
public Dictionary<Int64, string> Ns { get; set; } [JsonProperty]
private int Height { get; set; }
}

自定义输出JSON类:

using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public class LimitPropsContractResolver : DefaultContractResolver
{
private string[] props = null; public LimitPropsContractResolver(string[] props)
{
this.props = props;
} protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> list = base.CreateProperties(type, memberSerialization); //只保留清單有列出的屬性
return list.Where(p => props.Contains(p.PropertyName)).ToList();
}
}

测试代码:

var textJson = "{\"get\":1245736642,\"ns\":{\"123\":\"秋香\",\"5927\":\"华安\",\"11232\":\"小强\"}}";
var model = Newtonsoft.Json.JsonConvert.DeserializeObject<Test>(textJson);
var settings = new JsonSerializerSettings();
settings.ContractResolver = new LimitPropsContractResolver("get,ns".Split(','));
var json = Newtonsoft.Json.JsonConvert.SerializeObject(model, settings);
//{"get":1245736642,"ns":{"123":"秋香","5927":"华安","11232":"小强"}}
var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(model);
//{"get":1245736642,"ns":{"123":"秋香","5927":"华安","11232":"小强"},"Height":0}