.Net 【工作应用】 Newtonsoft.Json用法
引用
using Newtonsoft.Json
一般用法
JsonConvert.SerializeObject({})
JsonConvert.DeserializeObject<T>(jsonString)
控制序列化字段
序列化的模式:OptOut 和 OptIn
忽略某些字段
[JsonObject(MemberSerialization.OptOut)] //默认,可以不标注
public class User
{
public string Name { get; set; }
public string Sex { get; set; }
[JsonIgnore]
public bool IDCard { get; set; }
public DateTime Birthday { get; set; }
}
只需要某些字段
[JsonObject(MemberSerialization.OptIn)]
public class User
{
[JsonProperty]
public string Name { get; set; }
public string Sex { get; set; }
public bool IDCard { get; set; }
public DateTime Birthday { get; set; }
}
null值处理
通过JsonSerializerSettings配置
JsonSerializerSettings jsetting=new JsonSerializerSettings();
jsetting.NullValueHandling = NullValueHandling.Ignore;
JsonConvert.SerializeObject(obj, Formatting.Indented, jsetting);
通过JsonProperty设置
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
public DateTime? Birthday { get; set; }
日期格式化
JsonSerializerSettings jsetting=new JsonSerializerSettings();
jsetting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
jsetting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
自定义字段名称
[JsonProperty(PropertyName = "CName")]
public string Name { get; set; }
枚举类型序列化
显示enmu的string
enmu UserType
{
normal = 0,
admin = 1
}
[JsonConverter(typeof(StringEnumConverter))]
public UserType Type { get; set; }
全局序列化设置
var setting = new JsonSerializerSettings();
JsonConvert.DefaultSettings = new Func<JsonSerializerSettings>(() =>
{
//日期类型默认格式化处理
setting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
//空值处理
setting.NullValueHandling = NullValueHandling.Ignore;
return setting;
});