码迷,mamicode.com
首页 > Windows程序 > 详细

C#对实体进行JSON序列化时枚举的处理

时间:2016-02-03 18:20:51      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

实体类如下:

技术分享
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;
    }
}
View Code

通过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序列化时枚举的处理

标签:

原文地址:http://www.cnblogs.com/duanjt/p/5180202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!