千家信息网

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

发表于:2025-11-17 作者:千家信息网编辑
千家信息网最后更新 2025年11月17日,这篇文章主要讲解了"怎么从json字符串自动生成C#类",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"怎么从json字符串自动生成C#类"吧!json转
千家信息网最后更新 2025年11月17日怎么从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安全错误 数据库的锁怎样保障安全 构成数据库的结构是什么 js读取api中的数据库 杭州广东网络安全培训 软件开发映射的3个概念 服务器管理设置工具下载 vf数据库如何输出 orcl数据库怎么开启审计功能 数据库逆向工程软件 J软件开发公司于2007年 湖北移动网络技术岗工资怎么样 一个数据中心机柜放几个服务器 六安市网络技术服务 大型数据库需要多大空间 河南专业软件开发服务应用 网络安全学习教育培训班 数据库管理系统常用的类型 学网络安全用什么电脑比较好 自己买电脑怎么搭建服务器 华为服务器555是什么故障 谈谈你对大数据库技术课程的认识 数据库中添加字段 湖北省网络安全知识竞赛题 操作sql数据库实例 网络安全刘胜利 工业网络安全与工控安全 生活日常注意网络安全问题 中学生的网络安全教育视频 查找另一个表格中的数据库 怀旧服各个服务器上线时间 如何查看云服务器配置
0