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

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

  


 json转类对象

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

1、添加引用 System.Web.Extensions

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

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

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

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

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

 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
{
/// <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 = ;
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 > )
{
var item = jsArray[];
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;
}
}
}
}

调用方式:

 JsonHelper helper = new JsonHelper(true);
try
{
this.txtOutPut.Text = helper.GetClassString("json字符串");
}
catch
{
this.txtOutPut.Text = "输入内容不符合规范...";
}

最后如果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. 【集训笔记】归纳与递推【HDOJ1297

    例:(2050)折线分割平面 问题描述: 平面上有n条折线,问这些折线最多能将平面分割成多少块? 样例输入 1 2 样例输出 2 7 平面上有n条折线,问这些折线最多能将平面分割成多少块? 解: 折线 ...

  2. Qt学习:线程间共享数据(使用信号槽传递数据,必须提前使用qRegisterMetaType来注册参数的类型)

    Qt线程间共享数据主要有两种方式: 使用共享内存.即使用一个两个线程都能够共享的变量(如全局变量),这样两个线程都能够访问和修改该变量,从而达到共享数据的目的: 使用singal/slot机制,把数据 ...

  3. Windows Phone 8初学者开发—第19部分:设置RecordAudio.xaml页面

    原文 Windows Phone 8初学者开发—第19部分:设置RecordAudio.xaml页面 原文地址:  http://channel9.msdn.com/Series/Windows-Ph ...

  4. Android的BUG(四) - Android app的卡死问题

    做android,免不了要去运行一些跑分程序,常用的跑分程序有quadrant(象限),nbench,安兔兔等.作为系统工程师,对这些跑分 程序都非常的不屑,这个只能是一个不客观的参考,但客户都喜欢拿 ...

  5. [译]URL和URI的区别

    译者:华科小涛:http://www.cnblogs.com/hust-ghtao/: 初学http协议,就被这两个相似的术语搞蒙了,查了很多资料,总算搞清楚了.(找资料还是英文啊,靠谱...). 本 ...

  6. 闲扯 Javascript 04 滚动条

    物体运动基础 让Div移动起来 offsetLeft的作用 用定时器让物体连续移动 效果原理 让ul一直向左移动 复制li innerHTML和+= 修改ul的width 滚动过界后,重设位置 判断过 ...

  7. IntelliJ IDEA导出Java 可执行Jar包

    原文:IntelliJ IDEA导出Java 可执行Jar包 保证自己的Java代码是没有问题的,在IDEA里面是可以正常运行的,然后,按下面步骤: 打开File -> Project Stru ...

  8. mockito中两种部分mock的实现,spy、callRealMethod

    什么是类的部分mock(partial mock)?A:部分mock是说一个类的方法有些是实际调用,有些是使用mockito的stubbing(桩实现). 为什么需要部分mock? A:当需要测试一个 ...

  9. 手游接入Facebook的那些坑

    之前工作须要在手游中接入了facebook,并以此写了<手游接入Facebook功能>的博文.当时facebook sdk的版本号还是3.x.代码集成度比較低.集成起来也比較麻烦.文中仅仅 ...

  10. Linux/Kubuntu/Ubuntu下安装字体

    1>获得字体文件*.ttf,免费下载地址:http://www.font5.com.cn/ simfang.ttf 仿宋体 simhei.ttf 黑体 simkai.ttf 楷体 simsun. ...