标签:
实体类如下:
public enum ESex { Boy, Girl } public class Person { public String Name { get; set; } public String Address { get; set; } public String Age { get; set; } public ESex Sex { get; set; } public Person() { } public Person(String name, String address, String age) { this.Name = name; this.Address = address; this.Age = age; } }
通过Newtonsoft.Json.dll进行序列化如下:
List<Person> list = new List<Person>(); for (int i = 0; i < 2; i++) { Person p = new Person("张三" + i, "重庆" + i, "2" + i); p.Sex = ESex.Girl; list.Add(p); } var result=JsonConvert.SerializeObject(list);
结果为:[{"Name":"张三0","Address":"重庆0","Age":"20","Sex":1},{"Name":"张三1","Address":"重庆1","Age":"21","Sex":1}]
可以看出Sex直接转换成了1,也就是说枚举默认从0开始排序,Girl就表示1,但是如果我们想要得到{"Name":"张三1","Address":"重庆1","Age":"21","Sex":"Girl"}结果怎么办呢?
解决方案:在Sex上面加入JsonConverter说明如下:
public class Person { public String Name { get; set; } public String Address { get; set; } public String Age { get; set; } [JsonConverter(typeof(StringEnumConverter))] public ESex Sex { get; set; } public Person() { } public Person(String name, String address, String age) { this.Name = name; this.Address = address; this.Age = age; } }
这样修改后得到的结果如下:
[{"Name":"张三0","Address":"重庆0","Age":"20","Sex":"Girl"},{"Name":"张三1","Address":"重庆1","Age":"21","Sex":"Girl"}]
这样实现后反序列化同样能够成功
标签:
原文地址:http://www.cnblogs.com/duanjt/p/5180202.html