zoukankan      html  css  js  c++  java
  • Json.NET序列化后包含类型,保证序列化和反序列化的对象类型相同(转载)

    This sample uses the TypeNameHandling setting to include type information when serializing JSON and read type information so that the create types are created when deserializing JSON.

    Sample


      

    Types

    public abstract class Business
    {
        public string Name { get; set; }
    }
    
    public class Hotel : Business
    {
        public int Stars { get; set; }
    }
    
    public class Stockholder
    {
        public string FullName { get; set; }
        public IList<Business> Businesses { get; set; }
    }

    Usage

    Stockholder stockholder = new Stockholder
    {
        FullName = "Steve Stockholder",
        Businesses = new List<Business>
        {
            new Hotel
            {
                Name = "Hudson Hotel",
                Stars = 4
            }
        }
    };
    
    string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.All
    });
    
    Console.WriteLine(jsonTypeNameAll);
    // {
    //   "$type": "Newtonsoft.Json.Samples.Stockholder, Newtonsoft.Json.Tests",
    //   "FullName": "Steve Stockholder",
    //   "Businesses": {
    //     "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business, Newtonsoft.Json.Tests]], mscorlib",
    //     "$values": [
    //       {
    //         "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
    //         "Stars": 4,
    //         "Name": "Hudson Hotel"
    //       }
    //     ]
    //   }
    // }
    
    string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder, Formatting.Indented, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Auto
    });
    
    Console.WriteLine(jsonTypeNameAuto);
    // {
    //   "FullName": "Steve Stockholder",
    //   "Businesses": [
    //     {
    //       "$type": "Newtonsoft.Json.Samples.Hotel, Newtonsoft.Json.Tests",
    //       "Stars": 4,
    //       "Name": "Hudson Hotel"
    //     }
    //   ]
    // }
    
    // for security TypeNameHandling is required when deserializing
    Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto, new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Auto
    });
    
    Console.WriteLine(newStockholder.Businesses[0].GetType().Name);
    // Hotel

    演示


    现在我们来做个演示,新建一个.NET Core控制台项目,然后我们定义两个类Car和Person如下:

    using Newtonsoft.Json;
    using System;
    
    namespace JsonNetTesting
    {
        public class Car
        {
            public string Name { get; set; }
            public string Color { get; set; }
        }
    
        public class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public Car carField;
            public Car CarProperty
            {
                get;
                set;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Person person = new Person()
                {
                    Name = "Jack",
                    Age = 35,
                    carField = new Car()
                    {
                        Name = "Benz",
                        Color = "Black"
                    },
                    CarProperty = new Car()
                    {
                        Name = "BMW",
                        Color = "White"
                    }
                };
    
                string json = JsonConvert.SerializeObject(person, new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All,
                    Formatting = Formatting.Indented
                });
    
                Console.WriteLine(json);
    
                person = JsonConvert.DeserializeObject<Person>(json, new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.All
                });
    
                Console.WriteLine("Press key to end...");
                Console.ReadKey();
            }
        }
    }

    可以看到当我们设置TypeNameHandling = TypeNameHandling.All后,本例中类Car和Person序列化为JSON后如下:

    {
      "$type": "JsonNetTesting.Person, JsonNetTesting",
      "carField": {
        "$type": "JsonNetTesting.Car, JsonNetTesting",
        "Name": "Benz",
        "Color": "Black"
      },
      "Name": "Jack",
      "Age": 35,
      "CarProperty": {
        "$type": "JsonNetTesting.Car, JsonNetTesting",
        "Name": "BMW",
        "Color": "White"
      }
    }

    可以看到类Car和Person被序列化为JSON后,都自动生成了一个"$type"属性,用来标识它们是从什么.NET类型序列化而来的。

    原文链接

  • 相关阅读:
    (cocos2d-js游戏)測试你的反应速度----------基本逻辑(上)
    Ubuntu上安装flashplayer
    多线程中的&quot;断点&quot;续传《notify()和wait()》
    HTML高级标签之表格标签
    leetcode
    4星|《经济学通识课》:深入浅出的经济学思想发展简史
    1星|《追随》:洞察力太差,有效信息太少,咨询经验太少(举的例子以跟自己孩子的互动为主)
    3星|《在苍茫中传灯》:国外投资业经典图书的内容介绍与学习心得
    2星|《新物种爆炸》:用自造的新名词把已知事情换了个说法。语文与逻辑都比较差。
    老钱观美业
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/10291556.html
Copyright © 2011-2022 走看看