简单实体Json序列化(输出JSON的属性可变)

简单实体Json序列化(输出JSON的属性可变)javascript

 

1、先看效果java

 

 

能够看出 , 咱们在序列化一个对像时, 只给出了 咱们想要 输出的两个字段名,  实际实体有5个属性, 通过可变属性序列化后的JSON 结果,也是咱们想要的。web

 

2、正式上程序json

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace TaskConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {


            var p = new Person { Age = 20, Name = "jinshuai", Meney = 3, Tex = 1, Berthday = DateTime.Now };

            var s = new PropertyVariableJsonSerializer();

            var result = s.Serialize<Person>(p, new List<string>() { "Name", "Age" });


            Console.WriteLine(result);
        


            Console.WriteLine("----------------------------");

            Console.Read();
            
        }
    }

 

 1   public class Person
 2     {
 3         public string Name { get; set; }
 4 
 5         public int Age { get; set; }
 6 
 7         public double Meney { get; set; }
 8 
 9         public double Tex { get; set; }
10 
11         public DateTime Berthday { get; set; }
12 
13     }

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Web.Script.Serialization;
 6 
 7 namespace TaskConsoleApplication
 8 {
 9 
10     /// <summary>
11     ///简单实体 可变属性序列化器
12     /// </summary>
13     public class PropertyVariableJsonSerializer
14     {
15         readonly JavaScriptSerializer _serializer = new JavaScriptSerializer();
16 
17         /// <summary>
18         /// json 序列化
19         /// </summary>
20         /// <typeparam name="T"></typeparam>
21         /// <param name="obj"></param>
22         /// <param name="propertys"></param>
23         /// <returns></returns>
24         public string Serialize<T>(T obj,List<string> propertys)
25         {
26             _serializer.RegisterConverters(new[] { new PropertyVariableConveter(typeof(T), propertys) });
27 
28             return _serializer.Serialize(obj);
29 
30         }
31     }
32 
33 
34     public class PropertyVariableConveter : JavaScriptConverter
35     {
36         private readonly List<Type> _supportedTypes = new List<Type>();
37 
38         public PropertyVariableConveter(Type supportedType, List<string> propertys)
39         {
40             _supportedTypes.Add(supportedType);
41             Propertys = propertys;
42 
43         }
44 
45 
46         private List<string> Propertys { get; set; }
47 
48 
49         public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
50         {
51 
52             throw new Exception("  这个暂时不支持 , 谢谢 ");
53 
54         }
55 
56         public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
57         {
58             var dic = new Dictionary<string, object>();
59 
60             var t = obj.GetType();
61              var properties= t.GetProperties();
62 
63              foreach (var ite in properties)
64              {
65                  string key = ite.Name;
66                  var v = t.GetProperty(key).GetValue(obj, null);
67 
68                  if (Propertys == null || Propertys.Count<=0)
69                  {
70                      dic.Add(key, v);
71                      continue;
72                  }
73 
74                  if (Propertys.Contains(key))
75                  {
76                      dic.Add(key, v);
77                  }
78              }
79 
80             return dic;
81 
82         }
83 
84         public override IEnumerable<Type> SupportedTypes
85         {
86             get { return _supportedTypes; }
87         }
88     }
89 }

 

嗯。 就这些吧。 只是玩玩而以。 app

 

此次 源代码 就不上了。ide

 

 

附:函数

 

使用 JavaScriptConverter 类能够为 JavaScriptSerializer 类自己不支持的托管类型实现序列化和反序列化进程。此外,若是须要对序列化和反序列化进程进行更多控制,还可使用 JavaScriptConverter。ui

SupportedTypes 属性指示自定义转换器为其提供转换器服务的类型。spa

若要指示 JavaScriptSerializer 实例必须使用自定义转换器,必须向该实例注册该转换器。若是要直接使用 JavaScriptSerializer 类,则应使用RegisterConverters 方法注册该转换器。不然,若是要从 ECMAScript (JavaScript) 调用 Web 方法而且但愿使用自定义转换器,则能够经过在配置文件中添加 converters 元素来注册该转换器。有关详细信息,请参阅How to: Configure ASP.NET Services in Microsoft Ajax3d

当 JavaScriptSerializer 实例序列化自身注册有自定义转换器的类型时,序列化程序将调用 Serialize 方法。一样,若是 JavaScriptSerializer 实例正在反序列化 JavaScript 对象符号 (JSON) 字符串而且识别出该 JSON 字符串中的某个类型具备与其关联的自定义转换器,序列化程序也将调用Deserialize 方法。

 

 

构造函数
 
 
  名称 说明
System_CAPS_protmethod JavaScriptConverter()

初始化 JavaScriptConverter 类的新实例。

属性
 
 
  名称 说明
System_CAPS_pubproperty SupportedTypes

当在派生类中重写时,获取受支持类型的集合。

方法
 
 
  名称 说明
System_CAPS_pubmethod Deserialize(IDictionary<String, Object>, Type, JavaScriptSerializer)

当在派生类中重写时,将所提供的字典转换为指定类型的对象。

System_CAPS_pubmethod Equals(Object)

肯定指定的对象是否等于当前对象。(从 Object 继承。)

System_CAPS_protmethod Finalize()

在垃圾回收将某一对象回收前容许该对象尝试释放资源并执行其余清理操做。(从 Object 继承。)

System_CAPS_pubmethod GetHashCode()

做为默认哈希函数。(从 Object 继承。)

System_CAPS_pubmethod GetType()

获取当前实例的 Type。(从 Object 继承。)

System_CAPS_protmethod MemberwiseClone()

建立当前 Object 的浅表副本。(从 Object 继承。)

System_CAPS_pubmethod Serialize(Object, JavaScriptSerializer)

当在派生类中重写时,生成名称/值对的字典。

System_CAPS_pubmethod ToString()

返回表示当前对象的字符串。(从 Object 继承。)

 

 

此次够 150 字了吧。 

相关文章
相关标签/搜索