分享
 
 
 

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

王朝学院·作者佚名  2016-05-20
窄屏简体版  字體: |||超大  

也谈C#之Json,从Json字符串到类代码阅读目录

json转类对象逆思考从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 TestModel20 {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#的对象。

这里引用了,Microsoft.JScript.dll 类库。

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 = 0; 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 else105 {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 else142 {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 > 0)163 {164

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有