JSON生成c#类代码小工具
JSON生成c#类代码小工具
为什么写这么个玩意
最近的项目中需要和一个服务端程序通讯,而通讯的协议是基于流行的json,由于是.net,所以很简单的从公司代码库里找到了Newtonsoft.dll(json.net),但是悲剧的是这个dll居然是很老的版本,没有Newtonsoft.Json.Linq、没有JObject,也就是说,如果想使用json必须json字符序列化为.net对象才行,这时问题来了,json格式无比的复杂,如果我一个一个对着json去定义class代码,实在是显得有点蠢了,所以百度了一下,还真找到了一个工具http://json2csharp.chahuo.com/,但是这个工具对我来说有一点点不爽,我的json中属性的值,我希望将它生成为.net中属性的注释如:如
{
name:"用户名",password:"密码"
}
生成
public class Root
{
/// <summary>
/// 用户名
/// <summary>
public string name { get; set; }
/// <summary>
/// 密码
///</summary>
public string password { get; set; }
}
而该工具貌似不可以,于是使用js写了简单的小工具,(测试数据json来自于:http://www.juhe.cn/docs/api/id/39(不是广告,我随便找的))如下:
代码
<html>
<head>
<title>json生成c#类</title>
<link rel="stylesheet" href="http://js.chahuo.com/prettify/prettify.css">
<script language="javascript" type="text/javascript" src="http://js.chahuo.com/prettify/prettify.js"></script>
<script type="text/javascript" src="http://tool.oschina.net/js/jsbeautify.js"></script>
</head>
<body>
<h1>json生成C#类小工具</h1>
<h5>JSON 字符串</h5>
<div>
<textarea style="width:600px;height:300px;margin-bottom:5px;" id="jsonStr"></textarea>
<br>
<button onclick="document.getElementById('jsonStr').value='';document.getElementById('class').innerHTML=''">清除</button>
<button onclick="do_js_beautify()">格式化代码</button>
<button onclick="startGen()">生成C#类</button>
</div>
<h5>C#类代码 <button onclick="selectCode()">选中代码</button></h5>
<pre class="prettyprint" id="class" style="border:1px solid #ccc; padding:10px; width:800px;">
</pre>
<script>
String.prototype.format = function(){
var args = arguments;
return this.replace(/\{(\d+)\}/g,
function(m,i){
return args[i];
});
}
String.prototype.trim=function(){
return this.replace(/(^\s*)|(\s*$)/g,"");
}
JSON2CSharp={
_allClass:[],
_genClassCode:function(obj,name){
var clas="public class {0}\r\n{\r\n".format(name || "Root");
for(var n in obj){
var v = obj[n];
n = n.trim();
clas += " {0} public {1} {2} { get; set; }\r\n\r\n".format(this._genComment(v),this._genTypeByProp(n,v),n);
}
clas += "}\r\n\r\n";
this._allClass.push(clas);
return this._allClass.join("\r\n\r\n");
},
_genTypeByProp:function(name,val){
switch(Object.prototype.toString.apply(val)){
case "[object Number]" :{
return val.toString().indexOf(".") > -1 ? "double" : "int";
}
case "[object Date]":{
return "DateTime";
}
case "[object Object]":{
name = name.substring(0,1).toUpperCase() + name.substring(1);
this._genClassCode(val,name);
return name;
}
case "[object Array]":{
return "List<{0}>".format(this._genTypeByProp(name+"Item",val[0]));
}
default:{
return "string";
}
}
},
_genComment:function(val){
var commm= typeof(val) == "string" && /.*[\u4e00-\u9fa5]+.*$/.test(val) ? val : "" ;
return "/// <summary>\r\n /// "+commm+ "\r\n /// </summary>\r\n";
},
convert:function(jsonObj){
this._allClass=[];
return this._genClassCode(jsonObj);
}
}
function do_js_beautify() {
var js_source =document.getElementById("jsonStr").value.replace(/^\s+/, '');
if(js_source.length==0)
return;
tabchar = ' ';
var fjs = js_beautify(js_source);
document.getElementById("jsonStr").value=fjs;
}
function startGen(){
try{
var v = eval("("+document.getElementById("jsonStr").value+")");
document.getElementById("class").className ="prettyprint";
document.getElementById("class").innerHTML=JSON2CSharp.convert(v);
prettyPrint();
document.getElementById("jsonStr").focus();
}catch(e){
alert(e.message);
}
}
function selectCode() {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById('class'));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById('class'));
window.getSelection().addRange(range);
}
}
</script>
</body>
</html>
原理非常简单,遍历json对象的属性,根据属性值的类型生成对应的类名即可, 这里不做详细介绍了。 代码写的有点丑,希望大家用得着。
JSON生成c#类代码小工具的更多相关文章
- JSON生成c#类代码小工具(转)
原文地址: http://www.cnblogs.com/tianqiq/archive/2015/03/02/4309791.html
- 也谈C#之Json,从Json字符串到类代码
原文:也谈C#之Json,从Json字符串到类代码 阅读目录 json转类对象 逆思考 从json字符串自动生成C#类 json转类对象 自从.net 4.0开始,微软提供了一整套的针对json进 ...
- EA生成实体类代码
引言 在做机房个人版重构的时候,就听说了EA是一个强大的软件.仅仅只是知道的时候,已经画完了图,没有怎么用EA其它的功能,所以一直没有见识过罢了.如今到了机房合作了,想到EA一定要好好用,这样能省不少 ...
- Jsonschema2pojo从JSON生成Java类(命令行)
1.说明 jsonschema2pojo工具可以从JSON Schema(或示例JSON文件)生成Java类型, 在文章Jsonschema2pojo从JSON生成Java类(Maven) 已经介绍过 ...
- JS-在线运行代码小工具
原理:window.open()方法,open一个新的空白页,然后把文本框中粘贴的代码通过DOM操作,写到新的代码页中, 再利用document.write的功能(写进去之前把其他的全部删掉,并且写进 ...
- SQL转Java代码小工具
工作中使用SQL的时候很多,当使用hibernate的时候,经常遇到多行的SQL,通常在PL/SQL或其他地方写好SQL,测试没问题后,需要将SQL写到程序代码中,多行SQL需要拼接字符串,手动一行行 ...
- 三个 DAL 相关的Java代码小工具
最近在做 DAL (Data Access Layer 数据访问层) 的服务化,发现有不少地方是人工编写比较繁琐的,因此写了几个小工具来完成. 1. 从 DAO 类自动生成 CoreService ...
- 一个Json结构对比的Python小工具兼谈编程求解问题
先上代码. jsondiff.py #!/usr/bin/python #_*_encoding:utf-8_*_ import argparse import json import sys rel ...
- Jsonschema2pojo从JSON生成Java类(Maven)
1.说明 jsonschema2pojo工具可以从JSON Schema(或示例JSON文件)生成Java类型, 并且可以配置生成Jackson 1.x,Jackson 2.x, Moshi 1.x或 ...
随机推荐
- Python基础学习-Python中最常见括号()、[]、{}的区别
Python中最常见括号的区别: 在Python语言中最常见的括号有三种,分别是:小括号().中括号[].花括号{}:其作用也不相同,分别用来代表不同的Python基本内置数据类型. Python中的 ...
- HDU 5053 the Sum of Cube(简单数论)
http://acm.hdu.edu.cn/showproblem.php?pid=5053 题目大意: 求出A^3+(A+1)^3+(A+2)^3+...+B^3和是多少 解题思路: 设f(n)=1 ...
- [转]Linux/Ubuntu sudo不用输入密码的方法
通常我们并不以root身份登录,但是当我们执行某些命令 (command)时需要用到root权限,我们通常都是用"sudo command"来执行command.由于使用Ubu ...
- 【转】mybatis实战教程(mybatis in action),mybatis入门到精通
MyBatis 目录(?)[-] mybatis实战教程mybatis in action之一开发环境搭建 mybatis实战教程mybatis in action之二以接口的方式编程 mybatis ...
- 个人训练记录-赛码"bestcoder"杯中国大学生程序设计冠军赛
A.Movie 题意是给n个线段,要求求出是否存在三个不相交的线段,是的话输出yes,否则输出no.根据贪心的想法,可以先找出右端点r'最小的线段,他是三条线段中最左的那条,再找出左端点l'最大的线段 ...
- javaSE基础第二篇
1.JDK下载: www.oracle.com 2.JAVA_HOME bin目录:存放可执行文件.exe 把可能变的路径写入JAVA_HOME path=......;%JAVA_HOME%%; ...
- java快速学习
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Java是面向对象语言.这门语言其实相当年轻,于1995年才出现,由Sun公司出品 ...
- URL请求工具
工作中有个需求,定期请求多个URL.“定期”采用计划任务实现,请求URL,虽说start url可以实现,但不灵活.自己制作了个专门请求URL的工具,并记录请求结果. 控制台程序代码: class P ...
- 缓解 SQL Server has encountered 727 occurrence(s) of I/O requests taking longer than 15 seconds
sql server 会记录IO等待时间超过15 seconds的请求,这时application会有 time out 现象,dba需要判断是workload,concurrecy 所致还是sql ...
- arm 2440 linux 应用程序 nes 红白机模拟器 第1篇
对比了很多种,开源的 NES 模拟器 VirtuaNES , nestopia , FakeNES , FCEUX , InfoNES , LiteNES 最后决定使用 LiteNES 进行移值,它是 ...