千家信息网

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

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章主要讲解了"怎么从json字符串自动生成C#类",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么从json字符串自动生成C#类"吧!json转
千家信息网最后更新 2026年11月03日怎么从json字符串自动生成C#类

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

json转类对象

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

1、添加引用 System.Web.Extensions

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字符串(抓包比较频繁)。每次遇到json字符串,大多需要解析,又要进行重复劳动,又需要定义一个C#对象类,有没有一个比较好的办法解决呢,不用每次都去写代码。自动生成多好。。。

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

从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要稍稍复杂一点。

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. {

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

  5. }

  6. catch

  7. {

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

  9. }

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

字符 字符串 C# 代码 对象 自动生成 生成 内容 类型 微软 处理 学习 测试 复杂 清楚 频繁 不用 入口 办法 单个 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网黑科技 互联网新科技 山东特亿宝互联网科技有限公司 互联网科技工作委员会副主任毛军 中国互联网科技工作委员会毛军 深圳恒合互联网络科技有限公司 互联网科技作文 新浪科技互联网 奔汉互联网科技 成都狮子座互联网科技 国外互联网科技网站 居家互联网科技有限公司 蓝色互联网科技 温州喔噻互联网科技有限公司 新兴科技互联网创新大赛颁奖典礼 阿里互联网科技企业 启辰互联网科技 富国互联网科技002692 从那以后互联网科技有限公司 互联网高科技行业有哪些企业 湖北九亚互联网络科技有限公司 中关村互联网科技集团 腾讯阿里互联网科技 合肥互联网科技公司 深圳艾佳互联网科技 千方科技属于互联网企业吗 洛阳共同富裕互联网科技有限公司 济南有互联网科技公司吗 宁波跨境商互联网科技有限公司 株洲百竞科技的互联网营销顾问
0