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

发布时间:2021-12-03 10:33:21 作者:iii
来源:亿速云 阅读:855

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

json转类对象

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

1、添加引用 System.Web.Extensions

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

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; }         }     }

输出内容:

怎么从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 {     /// <summary>     /// Json字符串zhuanh     /// </summary>     public class JsonHelper : IHelper     {         /// <summary>         /// 是否添加get set         /// </summary>         private bool isAddGetSet = false;          /// <summary>         /// 数据集合,临时         /// </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;             }         }     } }

调用方式:

  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#类这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 使用MyBatis Generator自动生成DAO以及实体类
  2. 从C#到TypeScript - Promise

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

json

上一篇:Linux磁盘管理中LVM逻辑卷基本概念及LVM的工作原理是什么

下一篇:tk.Mybatis插入数据获取Id怎么实现

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》