原文:也谈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. pyfits过滤数据更新文件。

    import pyfits as pf import numpy as np import matplotlib.pyplot as plt hdulist = pf.open("LE_ev ...

  2. excel列显示形式互换(字母与数字)

    以office2007为例: excel选项>公式>使用公式下的'R1C1引用样式' 打上钩显示形式为数字,不打钩显示形式为字母

  3. 17.1.1.3 Creating a User for Replication

    17.1.1.3 Creating a User for Replication 创建一个用户用于复制: 每个slave 连接到master 使用一个MySQL 用户名和密码, 因此必须有一个user ...

  4. 深入解析MFC -- 句柄与对象的关系

    CWnd::FromHandlePermanent ——根据窗口句柄得到CWnd*指针 This function, unlike FromHandle, does not create tempor ...

  5. MFC全局函数开局——AfxGetApp解剖

    MFC中有不少的全局函数,方便在不同对象中获取不同的内容或创建不同的对象.主要全局函数有: AfxWinInit() AfxBeginThread() AfxEndThread() AfxFormat ...

  6. matlab绘图方法汇总

    Matlab画图 强大的画图功能是Matlab的特点之中的一个,Matlab提供了一系列的画图函数,用户不须要过多的考虑画图的细节,仅仅须要给出一些基本參数就能得到所需图形,这类函数称为高层画图函数. ...

  7. android大牛高焕堂最新力作-android架构师之路

    android大牛高焕堂 个人介绍: Android专家顾问,台湾Android论坛主席,现任亚太地区Android技术大会主席,台湾Android领域框架开发联盟总架构师.发表100多篇Androi ...

  8. JAVA思维导图系列:多线程0基础

    感觉自己JAVA基础太差了,又一次看一遍,已思维导图的方式记录下来 多线程0基础 进程 独立性 拥有独立资源 独立的地址 无授权其它进程无法訪问 动态性 与程序的差别是:进程是动态的指令集合,而程序是 ...

  9. 为学Linux,我看了这些书

    为学Linux,我看了这些书   去年开始,抱着学习的态度开始了我的Linux学习,到现在,差不多一年了,收获很多,不敢说精通Linux,但是,还是对得起"略懂"这两个字的.这一年 ...

  10. VirtualBox虚拟机下Windows登录密码破解方法(阿里云推荐码:1WFZ0V,立享9折!)

    VirtualBox虚拟机下Windows登录密码破解方法 近两年虚拟机的发展给开发人员带来了极大便利,安装一个新环境,只需从别人那里copy一份虚拟机文件即可,分分钟搞定.我之前一直在Ubuntu下 ...