也谈C#之Json,从Json字符串到类代码

简介:

json转类对象

自从.net 4.0开始,微软提供了一整套的针对json进行处理的方案。其中,就有如何把json字符串转化成C#类对象,其实这段代码很多人都清楚,大家也都认识,我就不多说,先贴代码。

1、添加引用 System.Web.Extensions

 

2、测试一下代码

 
  1. static class Program 
  2.     { 
  3.         /// <summary> 
  4.         /// 程序的主入口点。 
  5.         /// </summary> 
  6.         static void Main() 
  7.         { 
  8.             string jsonStr = "{\"name\":\"supperlitt\",\"age\":25,\"likes\":[\"C#\",\"asp.net\"]}"
  9.             JavaScriptSerializer js = new JavaScriptSerializer(); 
  10.             var model = js.Deserialize<TestModel>(jsonStr); 
  11.  
  12.             Console.WriteLine(model.name); 
  13.             Console.WriteLine(model.age); 
  14.             Console.WriteLine(string.Join(",", model.likes)); 
  15.  
  16.             Console.ReadLine(); 
  17.         } 
  18.  
  19.         public class TestModel 
  20.         { 
  21.             public string name { getset; } 
  22.  
  23.             public int age { getset; } 
  24.  
  25.             public List<string> likes { getset; } 
  26.         } 
  27.     } 

输出内容:

逆思考

由于代码中,经常会遇到需要处理json字符串(抓包比较频繁)。每次遇到json字符串,大多需要解析,又要进行重复劳动,又需要定义一个C#对象类,有没有一个比较好的办法解决呢,不用每次都去写代码。自动生成多好。。。

于是LZ思前,向后,想到了以前用过的一个微软的类库,应该是微软的一个Com库。

     

从json字符串自动生成C#类

1、试着百度了一下,也尝试了几个可以使用的类。于是找到了

如下的代码,能够解析一个json字符串,成为一个C#的对象。

这里引用了,Microsoft.JScript.dll 类库。

 
 
  1. Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine(); 
  2. var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve); 

2、发现这个m对象,其实是一个JSObject对象,内部也可以继续进行细分,于是测试了种种,稍后会上源码。先看测试效果吧。

我们随便在web上面找了一个json字符串来进行处理。当然json要稍稍复杂一点。

 

ps:代码如下

 
  1. using System; 
  2. using System.Collections.Generic; 
  3. using System.Linq; 
  4. using System.Text; 
  5. using Microsoft.JScript; 
  6.  
  7. namespace Common 
  8.     /// <summary> 
  9.     /// Json字符串zhuanh 
  10.     /// </summary> 
  11.     public class JsonHelper : IHelper 
  12.     { 
  13.         /// <summary> 
  14.         /// 是否添加get set 
  15.         /// </summary> 
  16.         private bool isAddGetSet = false
  17.  
  18.         /// <summary> 
  19.         /// 数据集合,临时 
  20.         /// </summary> 
  21.         private List<AutoClass> dataList = new List<AutoClass>(); 
  22.  
  23.         public JsonHelper() 
  24.         { 
  25.         } 
  26.  
  27.         public JsonHelper(bool isAddGetSet) 
  28.         { 
  29.             this.isAddGetSet = isAddGetSet; 
  30.         } 
  31.  
  32.         /// <summary> 
  33.         /// 获取类的字符串形式 
  34.         /// </summary> 
  35.         /// <param name="jsonStr"></param> 
  36.         /// <returns></returns> 
  37.         public string GetClassString(string jsonStr) 
  38.         { 
  39.             Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine(); 
  40.             var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve); 
  41.  
  42.             int index = 0; 
  43.             var result = GetDicType((JSObject)m, ref index); 
  44.  
  45.             StringBuilder content = new StringBuilder(); 
  46.             foreach (var item in dataList) 
  47.             { 
  48.                 content.AppendFormat("\tpublic class {0}\r\n", item.CLassName); 
  49.                 content.AppendLine("\t{"); 
  50.                 foreach (var model in item.Dic) 
  51.                 { 
  52.                     if (isAddGetSet) 
  53.                     { 
  54.                         content.AppendFormat("\t\tpublic {0} {1}", model.Value, model.Key); 
  55.                         content.Append(" { get; set; }\r\n"); 
  56.                     } 
  57.                     else 
  58.                     { 
  59.                         content.AppendFormat("\t\tpublic {0} {1};\r\n", model.Value, model.Key); 
  60.                     } 
  61.  
  62.                     content.AppendLine(); 
  63.                 } 
  64.  
  65.                 content.AppendLine("\t}"); 
  66.                 content.AppendLine(); 
  67.             } 
  68.  
  69.             return content.ToString(); 
  70.         } 
  71.  
  72.         /// <summary> 
  73.         /// 获取类型的字符串表示 
  74.         /// </summary> 
  75.         /// <param name="type"></param> 
  76.         /// <returns></returns> 
  77.         private string GetTypeString(Type type) 
  78.         { 
  79.             if (type == typeof(int)) 
  80.             { 
  81.                 return "int"
  82.             } 
  83.             else if (type == typeof(bool)) 
  84.             { 
  85.                 return "bool"
  86.             } 
  87.             else if (type == typeof(Int64)) 
  88.             { 
  89.                 return "long"
  90.             } 
  91.             else if (type == typeof(string)) 
  92.             { 
  93.                 return "string"
  94.             } 
  95.             else if (type == typeof(List<string>)) 
  96.             { 
  97.                 return "List<string>"
  98.             } 
  99.             else if (type == typeof(List<int>)) 
  100.             { 
  101.                 return "List<int>"
  102.             } 
  103.             else 
  104.             { 
  105.                 return "string"
  106.             } 
  107.         } 
  108.  
  109.         /// <summary> 
  110.         /// 获取字典类型 
  111.         /// </summary> 
  112.         /// <returns></returns> 
  113.         private string GetDicType(JSObject jsObj, ref int index) 
  114.         { 
  115.             AutoClass classInfo = new AutoClass(); 
  116.  
  117.             var model = ((Microsoft.JScript.JSObject)(jsObj)).GetMembers(System.Reflection.BindingFlags.GetField); 
  118.             foreach (Microsoft.JScript.JSField item in model) 
  119.             { 
  120.                 string name = item.Name; 
  121.                 Type type = item.GetValue(item).GetType(); 
  122.                 if (type == typeof(ArrayObject)) 
  123.                 { 
  124.                     // 集合 
  125.                     string typeName = GetDicListType((ArrayObject)item.GetValue(item), ref index); 
  126.                     if (!string.IsNullOrEmpty(typeName)) 
  127.                     { 
  128.                         classInfo.Dic.Add(name, typeName); 
  129.                     } 
  130.                 } 
  131.                 else if (type == typeof(JSObject)) 
  132.                 { 
  133.                     // 单个对象 
  134.                     string typeName = GetDicType((JSObject)item.GetValue(item), ref index); 
  135.                     if (!string.IsNullOrEmpty(typeName)) 
  136.                     { 
  137.                         classInfo.Dic.Add(name, typeName); 
  138.                     } 
  139.                 } 
  140.                 else 
  141.                 { 
  142.                     classInfo.Dic.Add(name, GetTypeString(type)); 
  143.                 } 
  144.             } 
  145.  
  146.             index++; 
  147.             classInfo.CLassName = "Class" + index; 
  148.             dataList.Add(classInfo); 
  149.             return classInfo.CLassName; 
  150.         } 
  151.  
  152.         /// <summary> 
  153.         /// 读取集合类型 
  154.         /// </summary> 
  155.         /// <param name="jsArray"></param> 
  156.         /// <param name="index"></param> 
  157.         /// <returns></returns> 
  158.         private string GetDicListType(ArrayObject jsArray, ref int index) 
  159.         { 
  160.             string name = string.Empty; 
  161.             if ((int)jsArray.length > 0) 
  162.             { 
  163.                 var item = jsArray[0]; 
  164.                 var type = item.GetType(); 
  165.                 if (type == typeof(JSObject)) 
  166.                 { 
  167.                     name = "List<" + GetDicType((JSObject)item, ref index) + ">"
  168.                 } 
  169.                 else 
  170.                 { 
  171.                     name = "List<" + GetTypeString(type) + ">"
  172.                 } 
  173.             } 
  174.  
  175.             return name; 
  176.         } 
  177.     } 
  178.  
  179.     public class AutoClass 
  180.     { 
  181.         public string CLassName { getset; } 
  182.  
  183.         private Dictionary<stringstring> dic = new Dictionary<stringstring>(); 
  184.  
  185.         public Dictionary<stringstring> Dic 
  186.         { 
  187.             get 
  188.             { 
  189.                 return this.dic; 
  190.             } 
  191.             set 
  192.             { 
  193.                 this.dic = value; 
  194.             } 
  195.         } 
  196.     } 

调用方式:

 
 
  1. JsonHelper helper = new JsonHelper(true); 
  2. try 
  3.    this.txtOutPut.Text = helper.GetClassString("json字符串"); 
  4. catch 
  5.    this.txtOutPut.Text = "输入内容不符合规范..."
  6. }

最后如果dudu允许的话,我再附上一个测试地址吧:http://www.51debug.com/tool/JsonToCharpCode.aspx

博客也写了几次了,不过每次都写得比较滥,看着不舒服,这次用心写了一下,欢迎大家拍砖或提供更好的建议。


作者:Supper_litt

来源:51CTO 

相关文章
|
11天前
|
JSON JavaScript 前端开发
JavaScript原生代码处理JSON的一些高频次方法合集
JavaScript原生代码处理JSON的一些高频次方法合集
|
1月前
|
C#
C#学习相关系列之数据类型类的三大特性(二)
C#学习相关系列之数据类型类的三大特性(二)
|
1月前
|
C# Windows
C#通过代码实现快捷键编辑
C#通过代码实现快捷键编辑
|
1月前
|
C#
58.c#:directory类
58.c#:directory类
12 0
|
1月前
|
C#
57.c#:directorylnfo类
57.c#:directorylnfo类
13 0
|
1月前
|
监控 C#
55.c#:file类
55.c#:file类
16 1
|
1月前
|
算法 C#
54.c#:random类
54.c#:random类
14 1
|
1月前
|
C#
51.c#:string类的静态方法
51.c#:string类的静态方法
20 1
|
17天前
|
JSON 数据格式
Json字符串与QVariantList 对象相互转换
Json字符串与QVariantList 对象相互转换
6 0
|
29天前
|
C#
深入C#中的String类
深入C#中的String类
10 0