也谈C#之Json,从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库。
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字符串到类代码的更多相关文章
- js中的json对象和字符串之间的转化
字符串转对象(strJSON代表json字符串) var obj = eval(strJSON); var obj = strJSON.parseJSON(); var obj = JSO ...
- 小谈一下JavaScript中的JSON
一.JSON的语法可以表示以下三种类型的值: 1.简单值:字符串,数值,布尔值,null 比如:5,"你好",false,null JSON中字符串必须用双引号,而JS中则没有强制 ...
- js中json对象和字符串的转换
JSON.parse() : 字符串-->json对象 var str = '{"name":"huangxiaojian","age" ...
- JSon_零基础_006_将JSon格式的字符串转换为Java对象
需求: 将JSon格式的字符串转换为Java对象. 应用此技术从一个json对象字符串格式中得到一个java对应的对象. JSONObject是一个“name.values”集合, 通过get(key ...
- json对象与字符串互转
javascript 1 JSON.parse() 方法用于将一个 JSON 字符串转换为对象. JSON.parse(text[, reviver]) text:必需, 一个有效的 JSON 字符串 ...
- json格式的字符串转为json对象遇到特殊字符问题解决
中午做后台发过来的json的时候转为对象,可是有几条数据一直出不来,检查发现json里包含了换行符,造成这种情况的原因可能是编辑部门在编辑的时候打的回车造成的 假设有这样一段json格式的字符串 va ...
- 解决如下json格式的字符串不能使用DataContractJsonSerializer序列化和反序列化 分类: JSON 2015-01-28 14:26 72人阅读 评论(0) 收藏
可以解决如下json格式的字符串不能使用DataContractJsonSerializer反序列化 { "ss": "sss", " ...
- android实现json数据的解析和把数据转换成json格式的字符串
利用android sdk里面的 JSONObject和JSONArray把集合或者普通数据,转换成json格式的字符串 JSONObject和JSONArray解析json格式的字符串为集合或者一般 ...
- json对象转字符串与json字符串转对象
1.概述: 我们在编程时进场会遇到json对象转字符串,或者字符串转对象的情况. 2.解决办法: json.parse()方法是将json字符串转成json对象. json.stringfy()方法是 ...
随机推荐
- CodeForces 260A Adding Digits
这道题目的意思是给你提供a, b, n 三个数 a为 输入的数字 ,你需要在a后面加n次 ,每次可以加0-9 但要保证每次加上去的那个数字能被b整除 不过数据规模有点大,用搜索会MLE(即使开了个开栈 ...
- Ural 1149 - Sinus Dances
Let An = sin(1–sin(2+sin(3–sin(4+…sin(n))…)Let Sn = (…(A1+n)A2+n–1)A3+…+2)An+1For given N print SN I ...
- cocos2d-x游戏开发系列教程-超级玛丽01-前言
前言 上次用象棋演示了cocos2dx的基本用法,但是对cocos2dx并没有作深入的讨论,这次以超级马里奥的源代码为线索,我们一起来学习超级马里奥的实现,并以一些篇幅来详细讲述遇到的具体问题和具体的 ...
- 基于visual Studio2013解决算法导论之012计数排序
题目 计数排序 解决代码及点评 #include <stdio.h> #include <stdlib.h> #include <malloc.h> #in ...
- Zabbix Step 1 : Install CentOS6.5 and Configration
[root@myzabbix Desktop]#rpm -ivh http://repo.zabbix.com/zabbix/2.2/rhel/6/x86_64/zabbix-release-2.2- ...
- stm32之ADC
将模拟量转换为数字量的过程称为模式(A/D)转换,完成这一转换的期间成为模数转换器(简称ADC);将数字量转换为模拟量的过程为数模(D/A)转换,完成这一转换的器件称为数模转换器(简称DAC). 模拟 ...
- 查看htmlView
1.视图 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:too ...
- 最新Cocos2d-x3.2开发环境搭建(windows环境下)
原文地址:http://cache.baiducontent.com/c?m=9d78d513d9921cfe05ac837f7d16c067690297634d9dc7150ed58449e3735 ...
- javascript笔记整理(正则)
RegExp 对象表示正则表达式,它是对字符串执行模式匹配的强大工具 var re=/e/; var re=new RegExp('e'); 正则表达式的 String 对象的方法 1.search- ...
- Android TextView(同时显示图片+文字)
见上图:需要图片和文字 在一起 之前的做法是用两个控件组成 <LinearLayout> <ImageView /> <TextView /> </Linea ...