C#对实体进行JSON序列化时枚举的处理
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#对实体进行JSON序列化时枚举的处理相关的知识,希望对你有一定的参考价值。
实体类如下:
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"}]
这样实现后反序列化同样能够成功
以上是关于C#对实体进行JSON序列化时枚举的处理的主要内容,如果未能解决你的问题,请参考以下文章