也談C#之Json,從Json字符串到類代碼
json轉(zhuǎn)類對象
自從.net 4.0開始,微軟提供了一整套的針對json進行處理的方案。其中,就有如何把json字符串轉(zhuǎn)化成C#類對象,其實這段代碼很多人都清楚,大家也都認(rèn)識,我就不多說,先貼代碼。
1、添加引用 System.Web.Extensions
  
2、測試一下代碼
- static class Program
 - {
 - /// <summary>
 - /// 程序的主入口點。
 - /// </summary>
 - static void Main()
 - {
 - string jsonStr = "{\"name\":\"supperlitt\",\"age\":25,\"likes\":[\"C#\",\"asp.net\"]}";
 - JavaScriptSerializer js = new JavaScriptSerializer();
 - var model = js.Deserialize<TestModel>(jsonStr);
 - Console.WriteLine(model.name);
 - Console.WriteLine(model.age);
 - Console.WriteLine(string.Join(",", model.likes));
 - Console.ReadLine();
 - }
 - public class TestModel
 - {
 - public string name { get; set; }
 - public int age { get; set; }
 - public List<string> likes { get; set; }
 - }
 - }
 
輸出內(nèi)容:

逆思考
由于代碼中,經(jīng)常會遇到需要處理json字符串(抓包比較頻繁)。每次遇到j(luò)son字符串,大多需要解析,又要進行重復(fù)勞動,又需要定義一個C#對象類,有沒有一個比較好的辦法解決呢,不用每次都去寫代碼。自動生成多好。。。
于是LZ思前,向后,想到了以前用過的一個微軟的類庫,應(yīng)該是微軟的一個Com庫。
      
#p#
從json字符串自動生成C#類
1、試著百度了一下,也嘗試了幾個可以使用的類。于是找到了
如下的代碼,能夠解析一個json字符串,成為一個C#的對象。
這里引用了,Microsoft.JScript.dll 類庫。
- Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
 - var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve);
 
2、發(fā)現(xiàn)這個m對象,其實是一個JSObject對象,內(nèi)部也可以繼續(xù)進行細(xì)分,于是測試了種種,稍后會上源碼。先看測試效果吧。
我們隨便在web上面找了一個json字符串來進行處理。當(dāng)然json要稍稍復(fù)雜一點。
  
ps:代碼如下
- using System;
 - using System.Collections.Generic;
 - using System.Linq;
 - using System.Text;
 - using Microsoft.JScript;
 - namespace Common
 - {
 - /// <summary>
 - /// Json字符串zhuanh
 - /// </summary>
 - public class JsonHelper : IHelper
 - {
 - /// <summary>
 - /// 是否添加get set
 - /// </summary>
 - private bool isAddGetSet = false;
 - /// <summary>
 - /// 數(shù)據(jù)集合,臨時
 - /// </summary>
 - private List<AutoClass> dataList = new List<AutoClass>();
 - public JsonHelper()
 - {
 - }
 - public JsonHelper(bool isAddGetSet)
 - {
 - this.isAddGetSet = isAddGetSet;
 - }
 - /// <summary>
 - /// 獲取類的字符串形式
 - /// </summary>
 - /// <param name="jsonStr"></param>
 - /// <returns></returns>
 - public string GetClassString(string jsonStr)
 - {
 - Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
 - var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve);
 - int index = 0;
 - var result = GetDicType((JSObject)m, ref index);
 - StringBuilder content = new StringBuilder();
 - foreach (var item in dataList)
 - {
 - content.AppendFormat("\tpublic class {0}\r\n", item.CLassName);
 - content.AppendLine("\t{");
 - foreach (var model in item.Dic)
 - {
 - if (isAddGetSet)
 - {
 - content.AppendFormat("\t\tpublic {0} {1}", model.Value, model.Key);
 - content.Append(" { get; set; }\r\n");
 - }
 - else
 - {
 - content.AppendFormat("\t\tpublic {0} {1};\r\n", model.Value, model.Key);
 - }
 - content.AppendLine();
 - }
 - content.AppendLine("\t}");
 - content.AppendLine();
 - }
 - return content.ToString();
 - }
 - /// <summary>
 - /// 獲取類型的字符串表示
 - /// </summary>
 - /// <param name="type"></param>
 - /// <returns></returns>
 - private string GetTypeString(Type type)
 - {
 - if (type == typeof(int))
 - {
 - return "int";
 - }
 - else if (type == typeof(bool))
 - {
 - return "bool";
 - }
 - else if (type == typeof(Int64))
 - {
 - return "long";
 - }
 - else if (type == typeof(string))
 - {
 - return "string";
 - }
 - else if (type == typeof(List<string>))
 - {
 - return "List<string>";
 - }
 - else if (type == typeof(List<int>))
 - {
 - return "List<int>";
 - }
 - else
 - {
 - return "string";
 - }
 - }
 - /// <summary>
 - /// 獲取字典類型
 - /// </summary>
 - /// <returns></returns>
 - private string GetDicType(JSObject jsObj, ref int index)
 - {
 - AutoClass classInfo = new AutoClass();
 - var model = ((Microsoft.JScript.JSObject)(jsObj)).GetMembers(System.Reflection.BindingFlags.GetField);
 - foreach (Microsoft.JScript.JSField item in model)
 - {
 - string name = item.Name;
 - Type type = item.GetValue(item).GetType();
 - if (type == typeof(ArrayObject))
 - {
 - // 集合
 - string typeName = GetDicListType((ArrayObject)item.GetValue(item), ref index);
 - if (!string.IsNullOrEmpty(typeName))
 - {
 - classInfo.Dic.Add(name, typeName);
 - }
 - }
 - else if (type == typeof(JSObject))
 - {
 - // 單個對象
 - string typeName = GetDicType((JSObject)item.GetValue(item), ref index);
 - if (!string.IsNullOrEmpty(typeName))
 - {
 - classInfo.Dic.Add(name, typeName);
 - }
 - }
 - else
 - {
 - classInfo.Dic.Add(name, GetTypeString(type));
 - }
 - }
 - index++;
 - classInfo.CLassName = "Class" + index;
 - dataList.Add(classInfo);
 - return classInfo.CLassName;
 - }
 - /// <summary>
 - /// 讀取集合類型
 - /// </summary>
 - /// <param name="jsArray"></param>
 - /// <param name="index"></param>
 - /// <returns></returns>
 - private string GetDicListType(ArrayObject jsArray, ref int index)
 - {
 - string name = string.Empty;
 - if ((int)jsArray.length > 0)
 - {
 - var item = jsArray[0];
 - var type = item.GetType();
 - if (type == typeof(JSObject))
 - {
 - name = "List<" + GetDicType((JSObject)item, ref index) + ">";
 - }
 - else
 - {
 - name = "List<" + GetTypeString(type) + ">";
 - }
 - }
 - return name;
 - }
 - }
 - public class AutoClass
 - {
 - public string CLassName { get; set; }
 - private Dictionary<string, string> dic = new Dictionary<string, string>();
 - public Dictionary<string, string> Dic
 - {
 - get
 - {
 - return this.dic;
 - }
 - set
 - {
 - this.dic = value;
 - }
 - }
 - }
 - }
 
調(diào)用方式:
- JsonHelper helper = new JsonHelper(true);
 - try
 - {
 - this.txtOutPut.Text = helper.GetClassString("json字符串");
 - }
 - catch
 - {
 - this.txtOutPut.Text = "輸入內(nèi)容不符合規(guī)范...";
 - }
 
***如果dudu允許的話,我再附上一個測試地址吧:http://www.51debug.com/tool/JsonToCharpCode.aspx
博客也寫了幾次了,不過每次都寫得比較濫,看著不舒服,這次用心寫了一下,歡迎大家拍磚或提供更好的建議。















 
 
 

 
 
 
 