原文:也谈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. XCode 6 出现 no identity found: Command /usr/bin/codesign failed with exit code 1 解决方法汇总

    1, 解决办法,进入开发者账号重建一个 Provisioning Profiles(或配套证书) 文件,把证书添加正确就可以了 (应该是最有效的) 2, 将p12文件重新安装下 3, 在 iPhone ...

  2. Windows Phone 8初学者开发—第18部分:在页面间导航

    原文 Windows Phone 8初学者开发—第18部分:在页面间导航 原文地址:  http://channel9.msdn.com/Series/Windows-Phone-8-Developm ...

  3. ubuntu学习: apt-get命令

    1.apt-get update 更新软件源本地缓存文件 2.apt-cache search 查找软件包,找到想要安装的包,如 sudo apt-cache search mysql-server ...

  4. 基于visual Studio2013解决算法导论之054图的邻接矩阵表示

     题目 图的邻接矩阵表示 解决代码及点评 // 图的邻接矩阵表示.cpp : 定义控制台应用程序的入口点. // #include <iostream> #include <l ...

  5. quant_百度百科

    quant_百度百科     quant    编辑    quant的工作就是设计并实现金融的数学模型(主要采用计算机编程),包括衍生物定价,风险估价或预测市场行为等.所以quant更多可看为工程师 ...

  6. Android实现 再按一次退出 的三种方法 durationTime、timerTask 和Handler

    目前很多Android应用都会实现按返回键时提示“再按一次推退出” 在这篇文章中总结了各家的方法,一般都是监听Activity的onKeyDown 或者onBackPressed方法 方法一: 直接计 ...

  7. AES SHA-1 SM3 MD5

    AES是美国国家标准技术研究所NIST旨在代替DES的21世纪的加密标准. 输入:128bit 的消息分组 输出:128bit 的密文分组 密钥长度及圈数 128 10 192 12 256 14 消 ...

  8. OAuth2.0认证过程

    本文以腾讯微博为例,详细介绍OAuth2.0的认证过程. 在使用腾讯微博平台提供的API前,您需要做以下两步工作: 成为开发者,并申请appkey和appsecret 授权获取accesstoken ...

  9. 列表标题栏添加CheckBox(自定义HanderView的时候实现)

    前段时间项目上的要求,要实现一个列表(见下图1).类似网页上的列表,可以通过选中标题栏的复选框,实现全选或者全不选的功能.但是看了很久,都没看到Qt哪个方法可以实现在标题栏添加控件. 图1 要实现这样 ...

  10. docker学习笔记5:利用commit命令创建镜像 和 删除本地镜像

    一.概述 创建镜像有两种方法,一是用commit命令,二是用dockerfile方法(这个更常用,在下面文章介绍).本章介绍commit方法. 在介绍commit命令前,我们先回顾下对代码的版本控制, ...