资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

这篇文章主要讲解了“怎么从json字符串自动生成C#类”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么从json字符串自动生成C#类”吧!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名、网络空间、营销软件、网站建设、依兰网站维护、网站推广。

json转类对象

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

1、添加引用 System.Web.Extensions

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

2、测试一下代码

static class Program     {         ///          /// 程序的主入口点。         ///          static void Main()         {             string jsonStr = "{\"name\":\"supperlitt\",\"age\":25,\"likes\":[\"C#\",\"asp.net\"]}";             JavaScriptSerializer js = new JavaScriptSerializer();             var model = js.Deserialize(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 likes { get; set; }         }     }

输出内容:

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

逆思考

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

于是LZ思前,向后,想到了以前用过的一个微软的类库,应该是微软的一个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、发现这个m对象,其实是一个JSObject对象,内部也可以继续进行细分,于是测试了种种,稍后会上源码。先看测试效果吧。

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

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

ps:代码如下

using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.JScript;  namespace Common {     ///      /// Json字符串zhuanh     ///      public class JsonHelper : IHelper     {         ///          /// 是否添加get set         ///          private bool isAddGetSet = false;          ///          /// 数据集合,临时         ///          private List dataList = new List();          public JsonHelper()         {         }          public JsonHelper(bool isAddGetSet)         {             this.isAddGetSet = isAddGetSet;         }          ///          /// 获取类的字符串形式         ///          ///          ///          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();         }          ///          /// 获取类型的字符串表示         ///          ///          ///          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))             {                 return "List";             }             else if (type == typeof(List))             {                 return "List";             }             else             {                 return "string";             }         }          ///          /// 获取字典类型         ///          ///          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;         }          ///          /// 读取集合类型         ///          ///          ///          ///          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 dic = new Dictionary();          public Dictionary Dic         {             get             {                 return this.dic;             }             set             {                 this.dic = value;             }         }     } }

调用方式:

  1. JsonHelper helper = new JsonHelper(true); 

  2. try 

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

  4. catch 

  5.    this.txtOutPut.Text = "输入内容不符合规范..."; 

  6. }

感谢各位的阅读,以上就是“怎么从json字符串自动生成C#类”的内容了,经过本文的学习后,相信大家对怎么从json字符串自动生成C#类这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是创新互联,小编将为大家推送更多相关知识点的文章,欢迎关注!


文章标题:怎么从json字符串自动生成C#类
本文网址:http://cdkjz.cn/article/jciesp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220