怎么從json字符串自動生成C#類

這篇文章主要講解了“怎么從json字符串自動生成C#類”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“怎么從json字符串自動生成C#類”吧!

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:申請域名、網(wǎng)絡(luò)空間、營銷軟件、網(wǎng)站建設(shè)、依蘭網(wǎng)站維護(hù)、網(wǎng)站推廣。

json轉(zhuǎn)類對象

自從.net 4.0開始,微軟提供了一整套的針對json進(jìn)行處理的方案。其中,就有如何把json字符串轉(zhuǎn)化成C#類對象,其實(shí)這段代碼很多人都清楚,大家也都認(rèn)識,我就不多說,先貼代碼。

1、添加引用 System.Web.Extensions

 怎么從json字符串自動生成C#類

2、測試一下代碼

static class Program     {         /// <summary>         /// 程序的主入口點(diǎn)。         /// </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)容:

怎么從json字符串自動生成C#類

逆思考

由于代碼中,經(jīng)常會遇到需要處理json字符串(抓包比較頻繁)。每次遇到j(luò)son字符串,大多需要解析,又要進(jìn)行重復(fù)勞動,又需要定義一個C#對象類,有沒有一個比較好的辦法解決呢,不用每次都去寫代碼。自動生成多好。。。

于是LZ思前,向后,想到了以前用過的一個微軟的類庫,應(yīng)該是微軟的一個Com庫。

     怎么從json字符串自動生成C#類

從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對象,其實(shí)是一個JSObject對象,內(nèi)部也可以繼續(xù)進(jìn)行細(xì)分,于是測試了種種,稍后會上源碼。先看測試效果吧。

我們隨便在web上面找了一個json字符串來進(jìn)行處理。當(dāng)然json要稍稍復(fù)雜一點(diǎn)。

 怎么從json字符串自動生成C#類

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)用方式:

  1. JsonHelper helper = new JsonHelper(true); 

  2. try 

  3.    this.txtOutPut.Text = helper.GetClassString("json字符串"); 

  4. catch 

  5.    this.txtOutPut.Text = "輸入內(nèi)容不符合規(guī)范..."; 

  6. }

感謝各位的閱讀,以上就是“怎么從json字符串自動生成C#類”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對怎么從json字符串自動生成C#類這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

本文標(biāo)題:怎么從json字符串自動生成C#類
本文來源:http://bm7419.com/article38/jciesp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供面包屑導(dǎo)航、企業(yè)網(wǎng)站制作、域名注冊、外貿(mào)建站、Google、動態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

h5響應(yīng)式網(wǎng)站建設(shè)