当前位置:首页 > Windows程序 > 正文

【转】C# 解析JSON方法总结

2021-03-11 Windows程序

主要参考.NET/joyhen/article/details/24805899和

根据自己需求,做些测试、修改、整理。

使用Newtonsoft.Json

一、用JsonConvert序列化和反序列化。

实体类不用特殊处理,正常定义属性即可,控制属性是否被序列化参照高级用法1。

[csharp]  

 

 

技术分享

技术分享

public interface IPerson  

{  

    string FirstName  

    {  

        get;  

        set;  

    }  

    string LastName  

    {  

        get;  

        set;  

    }  

    DateTime BirthDate  

    {  

        get;  

        set;  

    }  

}  

public class Employee : IPerson  

{  

    public string FirstName  

    {  

        get;  

        set;  

    }  

    public string LastName  

    {  

        get;  

        set;  

    }  

    public DateTime BirthDate  

    {  

        get;  

        set;  

    }  

  

    public string Department  

    {  

        get;  

        set;  

    }  

    public string JobTitle  

    {  

        get;  

        set;  

    }  

  

    public string NotSerialize { get; set; }  

}  

public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>  

{  

    //重写abstract class CustomCreationConverter<T>的Create方法  

    public override IPerson Create(Type objectType)  

    {  

        return new Employee();  

    }  

}  

public class Product  

{  

    public string Name { get; set; }  

    public DateTime Expiry { get; set; }  

    public Decimal Price { get; set; }  

    public string[] Sizes { get; set; }  

    public string NotSerialize { get; set; }  

}  

1.序列化代码:

[csharp]  

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/59409.html