原文:也谈C#之Json,从Json字符串到类代码

 阅读目录
  1. json转类对象
  2. 逆思考
  3. 从json字符串自动生成C#类

  


 json转类对象

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

1、添加引用 System.Web.Extensions

2、测试一下代码

  1. static class Program
  2. {
  3. /// <summary>
  4. /// 程序的主入口点。
  5. /// </summary>
  6. static void Main()
  7. {
  8. string jsonStr = "{\"name\":\"supperlitt\",\"age\":25,\"likes\":[\"C#\",\"asp.net\"]}";
  9. JavaScriptSerializer js = new JavaScriptSerializer();
  10. var model = js.Deserialize<TestModel>(jsonStr);
  11.  
  12. Console.WriteLine(model.name);
  13. Console.WriteLine(model.age);
  14. Console.WriteLine(string.Join(",", model.likes));
  15.  
  16. Console.ReadLine();
  17. }
  18.  
  19. public class TestModel
  20. {
  21. public string name { get; set; }
  22.  
  23. public int age { get; set; }
  24.  
  25. public List<string> likes { get; set; }
  26. }
  27. }

输出内容:

 逆思考

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

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

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

1、试着百度了一下,也尝试了几个可以使用的类。于是找到了

如下的代码,能够解析一个json字符串,成为一个C#的对象。

  1. Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
  2. var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve);

2、发现这个m对象,其实是一个JSObject对象,内部也可以继续进行细分,于是测试了种种,稍后会上源码。先看测试效果吧。

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

ps:代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.JScript;
  6.  
  7. namespace Common
  8. {
  9. /// <summary>
  10. /// Json字符串zhuanh
  11. /// </summary>
  12. public class JsonHelper : IHelper
  13. {
  14. /// <summary>
  15. /// 是否添加get set
  16. /// </summary>
  17. private bool isAddGetSet = false;
  18.  
  19. /// <summary>
  20. /// 数据集合,临时
  21. /// </summary>
  22. private List<AutoClass> dataList = new List<AutoClass>();
  23.  
  24. public JsonHelper()
  25. {
  26. }
  27.  
  28. public JsonHelper(bool isAddGetSet)
  29. {
  30. this.isAddGetSet = isAddGetSet;
  31. }
  32.  
  33. /// <summary>
  34. /// 获取类的字符串形式
  35. /// </summary>
  36. /// <param name="jsonStr"></param>
  37. /// <returns></returns>
  38. public string GetClassString(string jsonStr)
  39. {
  40. Microsoft.JScript.Vsa.VsaEngine ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
  41. var m = Microsoft.JScript.Eval.JScriptEvaluate("(" + jsonStr + ")", ve);
  42.  
  43. int index = ;
  44. var result = GetDicType((JSObject)m, ref index);
  45.  
  46. StringBuilder content = new StringBuilder();
  47. foreach (var item in dataList)
  48. {
  49. content.AppendFormat("\tpublic class {0}\r\n", item.CLassName);
  50. content.AppendLine("\t{");
  51. foreach (var model in item.Dic)
  52. {
  53. if (isAddGetSet)
  54. {
  55. content.AppendFormat("\t\tpublic {0} {1}", model.Value, model.Key);
  56. content.Append(" { get; set; }\r\n");
  57. }
  58. else
  59. {
  60. content.AppendFormat("\t\tpublic {0} {1};\r\n", model.Value, model.Key);
  61. }
  62.  
  63. content.AppendLine();
  64. }
  65.  
  66. content.AppendLine("\t}");
  67. content.AppendLine();
  68. }
  69.  
  70. return content.ToString();
  71. }
  72.  
  73. /// <summary>
  74. /// 获取类型的字符串表示
  75. /// </summary>
  76. /// <param name="type"></param>
  77. /// <returns></returns>
  78. private string GetTypeString(Type type)
  79. {
  80. if (type == typeof(int))
  81. {
  82. return "int";
  83. }
  84. else if (type == typeof(bool))
  85. {
  86. return "bool";
  87. }
  88. else if (type == typeof(Int64))
  89. {
  90. return "long";
  91. }
  92. else if (type == typeof(string))
  93. {
  94. return "string";
  95. }
  96. else if (type == typeof(List<string>))
  97. {
  98. return "List<string>";
  99. }
  100. else if (type == typeof(List<int>))
  101. {
  102. return "List<int>";
  103. }
  104. else
  105. {
  106. return "string";
  107. }
  108. }
  109.  
  110. /// <summary>
  111. /// 获取字典类型
  112. /// </summary>
  113. /// <returns></returns>
  114. private string GetDicType(JSObject jsObj, ref int index)
  115. {
  116. AutoClass classInfo = new AutoClass();
  117.  
  118. var model = ((Microsoft.JScript.JSObject)(jsObj)).GetMembers(System.Reflection.BindingFlags.GetField);
  119. foreach (Microsoft.JScript.JSField item in model)
  120. {
  121. string name = item.Name;
  122. Type type = item.GetValue(item).GetType();
  123. if (type == typeof(ArrayObject))
  124. {
  125. // 集合
  126. string typeName = GetDicListType((ArrayObject)item.GetValue(item), ref index);
  127. if (!string.IsNullOrEmpty(typeName))
  128. {
  129. classInfo.Dic.Add(name, typeName);
  130. }
  131. }
  132. else if (type == typeof(JSObject))
  133. {
  134. // 单个对象
  135. string typeName = GetDicType((JSObject)item.GetValue(item), ref index);
  136. if (!string.IsNullOrEmpty(typeName))
  137. {
  138. classInfo.Dic.Add(name, typeName);
  139. }
  140. }
  141. else
  142. {
  143. classInfo.Dic.Add(name, GetTypeString(type));
  144. }
  145. }
  146.  
  147. index++;
  148. classInfo.CLassName = "Class" + index;
  149. dataList.Add(classInfo);
  150. return classInfo.CLassName;
  151. }
  152.  
  153. /// <summary>
  154. /// 读取集合类型
  155. /// </summary>
  156. /// <param name="jsArray"></param>
  157. /// <param name="index"></param>
  158. /// <returns></returns>
  159. private string GetDicListType(ArrayObject jsArray, ref int index)
  160. {
  161. string name = string.Empty;
  162. if ((int)jsArray.length > )
  163. {
  164. var item = jsArray[];
  165. var type = item.GetType();
  166. if (type == typeof(JSObject))
  167. {
  168. name = "List<" + GetDicType((JSObject)item, ref index) + ">";
  169. }
  170. else
  171. {
  172. name = "List<" + GetTypeString(type) + ">";
  173. }
  174. }
  175.  
  176. return name;
  177. }
  178. }
  179.  
  180. public class AutoClass
  181. {
  182. public string CLassName { get; set; }
  183.  
  184. private Dictionary<string, string> dic = new Dictionary<string, string>();
  185.  
  186. public Dictionary<string, string> Dic
  187. {
  188. get
  189. {
  190. return this.dic;
  191. }
  192. set
  193. {
  194. this.dic = value;
  195. }
  196. }
  197. }
  198. }

调用方式:

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

最后如果dudu允许的话,我再附上一个测试地址吧:http://www.51debug.com/tool/JsonToCharpCode.aspx

博客也写了几次了,不过每次都写得比较滥,看着不舒服,这次用心写了一下,欢迎大家拍砖或提供更好的建议。

也谈C#之Json,从Json字符串到类代码的更多相关文章

  1. js中的json对象和字符串之间的转化

    字符串转对象(strJSON代表json字符串)   var obj = eval(strJSON);   var obj = strJSON.parseJSON();   var obj = JSO ...

  2. 小谈一下JavaScript中的JSON

    一.JSON的语法可以表示以下三种类型的值: 1.简单值:字符串,数值,布尔值,null 比如:5,"你好",false,null JSON中字符串必须用双引号,而JS中则没有强制 ...

  3. js中json对象和字符串的转换

    JSON.parse() : 字符串-->json对象 var str = '{"name":"huangxiaojian","age" ...

  4. JSon_零基础_006_将JSon格式的字符串转换为Java对象

    需求: 将JSon格式的字符串转换为Java对象. 应用此技术从一个json对象字符串格式中得到一个java对应的对象. JSONObject是一个“name.values”集合, 通过get(key ...

  5. json对象与字符串互转

    javascript 1 JSON.parse() 方法用于将一个 JSON 字符串转换为对象. JSON.parse(text[, reviver]) text:必需, 一个有效的 JSON 字符串 ...

  6. json格式的字符串转为json对象遇到特殊字符问题解决

    中午做后台发过来的json的时候转为对象,可是有几条数据一直出不来,检查发现json里包含了换行符,造成这种情况的原因可能是编辑部门在编辑的时候打的回车造成的 假设有这样一段json格式的字符串 va ...

  7. 解决如下json格式的字符串不能使用DataContractJsonSerializer序列化和反序列化 分类: JSON 2015-01-28 14:26 72人阅读 评论(0) 收藏

    可以解决如下json格式的字符串不能使用DataContractJsonSerializer反序列化 {     "ss": "sss",     " ...

  8. android实现json数据的解析和把数据转换成json格式的字符串

    利用android sdk里面的 JSONObject和JSONArray把集合或者普通数据,转换成json格式的字符串 JSONObject和JSONArray解析json格式的字符串为集合或者一般 ...

  9. json对象转字符串与json字符串转对象

    1.概述: 我们在编程时进场会遇到json对象转字符串,或者字符串转对象的情况. 2.解决办法: json.parse()方法是将json字符串转成json对象. json.stringfy()方法是 ...

随机推荐

  1. 笔记之Cyclone IV 第一卷第二章Cyclone IV器件的逻辑单元和逻辑阵

    逻辑单元 (LE) 在 Cyclone IV 器件结构中是最小的逻辑单位.LE 紧密且有效的提供了高级功能的逻辑使用.每个 LE 有以下特性 ■ 一个四口输入的查找表 (LUT),以实现四种变量的任何 ...

  2. 我也来说说C#中的异步:async/await

    序 最近看了一些园友们写的有关于异步的文章,受益匪浅,写这篇文章的目的是想把自己之前看到的文章做一个总结,同时也希望通过更加通俗易懂的语言让大家了解"异步"编程. 1:什么是异步 ...

  3. QT5.6 编译SQLServer驱动

    简要说下编译的主要步骤 @1:打开vs2015的命令行编译环境 ‘ @2:进入到cd到源码目录:cd C:\Qt\Qt5.6.0\5.6\Src\qtbase\src\plugins\sqldrive ...

  4. 基于visual Studio2013解决C语言竞赛题之0516人来人往

     题目

  5. 九度OnlineJudge之1022:游船出租

    题目描述:     现有公园游船租赁处请你编写一个租船管理系统.当游客租船时,管理员输入船号并按下S键,系统开始计时:当游客还船时,管理员输入船号并按下E键,系统结束计时.船号为不超过100的正整数. ...

  6. [置顶] T-sql sql server 设置主键约束、标示列、唯一约束、默认值、约束、创建表

    ----选择数据库 use ythome go ----查看表是否存在 if Exists ( select * from sysobjects where name='sys_menu' and t ...

  7. BT基础知识简介

    1. 蓝牙概述   无线局域网的通信 适用范围:10米到100米(根据发射功率的class不同有所差别,典型的class2为10m,而class1为100m,class3为1m) 应用:   局域网络 ...

  8. 插件化—配置xml的辅助测试

    1.xml文件,xml文件在res/xml目录下 <?xml version="1.0" encoding="utf-8"?> <infos& ...

  9. WCF技术剖析之二十八:自己动手获取元数据[附源代码下载]

    原文:WCF技术剖析之二十八:自己动手获取元数据[附源代码下载] 元数据的发布方式决定了元数据的获取行为,WCF服务元数据架构体系通过ServiceMetadataBehavior实现了基于WS-ME ...

  10. PHP函数详细剖析之rtrim函数 By ACReaper

    string rtrim ( string $str [, string $charlist ] ) 这个函数很好理解.r表示右边.trim表示修剪.即右边修剪.默认修剪字符str右边的字符.默认修剪 ...