1. 程式人生 > >C# json 序列化 匿名物件序列號 指定物件序列化

C# json 序列化 匿名物件序列號 指定物件序列化

一、序列化
通常我們返回json物件給客戶端,需要新建一個類,因為有些資料對方是不需要,
就像一個類Person,裡面有欄位Name、Photo,而對方有要Photo也有不要Photo的,這個時候我們通過序列化 類指定
1.引入System.Web.Extensions
2.

     var p = new Person { Name = "yc的客戶", Photo = "hahaahh" };

            var s = new PropertyVariableJsonSerializer();

            string result1 = s.Serialize<
Person>(p, new List<string>() { "Name" }); string result2 = s.Serialize<Person>(p, new List<string>() { "Name", "Photo" }); Console.WriteLine(result1); Console.WriteLine(result2); Console.ReadLine();

這裡寫圖片描述

 public class Person
    {
        public
string Name { get; set; } public string Photo { get; set; } }

通用方法

 public class PropertyVariableJsonSerializer
    {
        readonly System.Web.Script.Serialization.JavaScriptSerializer _serializer = new JavaScriptSerializer();

        /**/
        /// <summary>  
        /// json 序列化  
/// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="propertys"></param> /// <returns></returns> public string Serialize<T>(T obj, List<string> propertys) { _serializer.RegisterConverters(new[] { new PropertyVariableConveter(typeof(T), propertys) }); return _serializer.Serialize(obj); } } public class PropertyVariableConveter : JavaScriptConverter { private readonly List<Type> _supportedTypes = new List<Type>(); public PropertyVariableConveter(Type supportedType, List<string> propertys) { _supportedTypes.Add(supportedType); Propertys = propertys; } private List<string> Propertys { get; set; } public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) { throw new Exception(" 這個暫時不支援 , 謝謝 "); } public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) { var dic = new Dictionary<string, object>(); var t = obj.GetType(); var properties = t.GetProperties(); foreach (var ite in properties) { string key = ite.Name; var v = t.GetProperty(key).GetValue(obj, null); if (Propertys == null || Propertys.Count <= 0) { dic.Add(key, v); continue; } if (Propertys.Contains(key)) { dic.Add(key, v); } } return dic; } public override IEnumerable<Type> SupportedTypes { get { return _supportedTypes; } } }

二、反序列化

我們獲取了一個json,但是我們不想寫類,這個時候我能就可以使用
引入Newtonsoft.Json;

   var p = new Person { Name = "yc的客戶", Photo = "hahaahh" };

            var s = new PropertyVariableJsonSerializer();

            string result1 = s.Serialize<Person>(p, new List<string>() { "Name" });
            string result2 = s.Serialize<Person>(p, new List<string>() { "Name", "Photo" });

   var jo2 = JsonConvert.DeserializeObject<dynamic>(result2);

   Console.WriteLine(jo2.Name);