C# Json序列化、反序列化匿名类型、动态类型dynamic

包:Newtonsoft.Json 13.0.0.0

环境:Net 4.5

Program:

Console.WriteLine("**************匿名类 序列化、反序列化*****************");
/* 匿名类 */
{
    var person = new { Name = "GongHui", Age = 28, Sex = "男" };
    string json = JsonConvert.SerializeObject(person);
    Console.WriteLine(json);


    string json1 = @"{'Name':'GongHui','Age':28,'Sex':'女'}";
    var person1 = JsonConvert.DeserializeAnonymousType(json1, person);
    Console.WriteLine("---------person1-------------");
    Console.WriteLine(person1.Name);
    Console.WriteLine(person1.Age);
    Console.WriteLine(person1.Sex);

    string json2 = @"{'Name':'Jack','Sex':'男'}";
    var person2 = JsonConvert.DeserializeAnonymousType(json2, person);
    Console.WriteLine("---------person2-------------");
    Console.WriteLine(person2.Name);
    Console.WriteLine(person2.Age);
    Console.WriteLine(person2.Sex);
}

Console.WriteLine("**************动态类型dynamic 序列化、反序列化*****************");

/* 动态类型dynamic */
{
    dynamic obj =new System.Dynamic.ExpandoObject();
    obj.Name = "czj";
    obj.Age = 16;
    string json = JsonConvert.SerializeObject(obj);
    Console.WriteLine(json);


    string json1 = @"{'Name':'GongHui','Age':28,'Sex':'女'}";
    dynamic obj1 = Newtonsoft.Json.JsonConvert.DeserializeObject(json1);
    Console.WriteLine(obj1.Name);
    Console.WriteLine(obj1.Age);
    Console.WriteLine(obj1.Sex);
}
Console.ReadKey();

本文转自 https://blog.csdn.net/czjnoe/article/details/120406251,如有侵权,请联系删除。

THE END
分享
二维码
< <上一篇
下一篇>>