前端时间一直用JSON.Net 现在总结一下
1. 用[JsonIgnore]来忽略类中不序列化的属性
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
[JsonIgnore]
public int ProductCode { get; set; } // omitted
}
2. 若想选择类中哪些成员进行序列化,可以在类上标记DataContract 属性,若类上已标记此Attribute,则类中所有成员都不会进行序列化,除非成员上有标记DataMember Attribute;即用 [DataMember]来序列化成员
[DataContract]
public class Product
{
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal Price { get; set; }
public int ProductCode { get; set; } // omitted by default
}
3. 只读属性也可以序列化
4. 日期属性:JSON.Net 会把日期用ISO 8601格式进行序列化。UTC日期格式后缀是以 "Z"结尾,本地时间会包含一个时间偏差
2012-07-27T18:51:45.53403Z // UTC
2012-07-27T11:51:45.53403-07:00 // Local
5. 处理对象循环引用问题,例如:如下2个类,相互引用,用JSON.NET进行序列化会报Error
public class Employee
{
public string Name { get; set; }
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
public Employee Manager { get; set; }
}
为解决此问题,有2种解决办法:
方法一:
Employee emp = new Employee();
JsonConvert.SerializeObject(emp, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore});
方法二:
public class Employee
{
public string Name { get; set; }
[JsonIgnore]
public Department Department { get; set; }
}
public class Department
{
public string Name { get; set; }
[JsonIgnore]
public Employee Manager { get; set; }
}
6. 序列化对象
JsonConvert.SerializeObject(emp);
string json = Newtonsoft.Json.JsonConvert.SerializeObject(emp, Newtonsoft.Json.Formatting.Indented); // 缩进输出
string included = Newtonsoft.Json.JsonConvert.SerializeObject( emp, Newtonsoft.Json.Formatting.Indented, //缩进
new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore } // 忽略Null对象输出 );
7. 反序列化对象
string emp = "{\"Name\":\"Alice\"}";
JsonConvert.DeserializeObject<Employee>(text);