JSON继承SerializationBinder序列化与反序列化包含对象名

来源:互联网 发布:js动态改变url参数 编辑:程序博客网 时间:2024/04/29 21:28

1.创建一个KnownTypesBinder继承SerializationBinder的对象,并把对象名添加到成员变量中.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Runtime.Serialization;namespace JSONDemo{    public class KnownTypesBinder : SerializationBinder    {        public IList<Type> KnowTypes { get; set; }        public override Type BindToType(string assemblyName, string typeName)        {            return KnowTypes.SingleOrDefault(t => t.Name == typeName);        }        public override void BindToName(Type serializedType, out string assemblyName, out string typeName)        {            assemblyName = null;            typeName = serializedType.Name;        }    }}


2.创建一个Car对象,并添加成员变量.

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace JSONDemo{    public class Car    {        public string Maker { get; set; }        public string Model { get; set; }    }}


3.序列化与反序列化包含了对象名.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using GongHuiNewtonsoft.Json;using GongHuiNewtonsoft.Json.Serialization;using GongHuiNewtonsoft.Json.Converters;namespace JSONDemo{    class Program    {        static void Main(string[] args)        {            KnownTypesBinder ktb = new KnownTypesBinder            {                KnowTypes = new List<Type> { typeof(Car) }            };            Car car = new Car            {                Maker = "BMW",                Model = "7.0"            };            string json = JsonConvert.SerializeObject(car, Formatting.Indented, new JsonSerializerSettings            {                TypeNameHandling = TypeNameHandling.Objects,                Binder = ktb            });            Console.WriteLine(json);            object obj = JsonConvert.DeserializeObject(json, new JsonSerializerSettings            {                TypeNameHandling = TypeNameHandling.Objects,                Binder = ktb            });            Console.WriteLine(obj.GetType().Name);        }    }}


4.运行的结果,注意:序列化结果中包含了对象名:Car

 

JSON源代码下载地址:http://download.csdn.net/detail/lovegonghui/9342751

0 0