04
2021
02

C# Json转Object兼容性测试(Newtonsoft.Json)

using System;
using Newtonsoft.Json;

namespace JsonToObject
{
    class Program
    {
        static void Main(string[] args)
        {
            // 原始字符串 {"c1":1,"c2":"2","c3":3}
            string json = "{\"c1\":1,\"c2\":\"2\",\"c3\":3}";

            // json字符串中的属性比object中多
            Obj1 obj1 = JsonConvert.DeserializeObject<Obj1>(json);
            Console.WriteLine(JsonConvert.SerializeObject(obj1));

            // json字符串中的属性和object中一致
            Obj2 obj2 = JsonConvert.DeserializeObject<Obj2>(json);
            Console.WriteLine(JsonConvert.SerializeObject(obj2));

            // json字符串中的属性比object中少
            Obj3 obj3 = JsonConvert.DeserializeObject<Obj3>(json);
            Console.WriteLine(JsonConvert.SerializeObject(obj3));

            // json字符串中的属性与object中大小写不一致且类型不一致
            Obj4 obj4 = JsonConvert.DeserializeObject<Obj4>(json);
            Console.WriteLine(JsonConvert.SerializeObject(obj4));

            Console.ReadKey();

            // 输出结果
            /*
            {"c1":1,"c2":"2"}
            {"c1":1,"c2":"2","c3":3}
            {"c1":1,"c2":"2","c3":3,"c4":null}
            {"c1":"1","C2":2,"c3":"3"}
             */
        }
    }

    public class Obj1
    {
        public int c1;
        public string c2;
    }

    public class Obj2
    {
        public int c1;
        public string c2;
        public int c3;
    }

    public class Obj3
    {
        public int c1;
        public string c2;
        public int c3;
        public int? c4;
    }

    public class Obj4
    {
        public string c1;
        public int C2;
        public string c3;
    }
}


« 上一篇 下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。