您的位置:首页 > Web前端 > JavaScript

JSON生成c#类代码小工具

2016-09-02 14:05 417 查看

为什么写这么个玩意

最近的项目中需要和一个服务端程序通讯,而通讯的协议是基于流行的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来自于:https://www.juhe.cn/docs/api/id/39(不是广告,我随便找的))如下:

json生成C#类小工具

JSON 字符串
{
"resultcode": "200",
"reason": "查询成功!",
"result": {
"sk": { /*当前实况天气*/
"temp": "21", /*当前温度*/
"wind_direction": "西风", /*当前风向*/
"wind_strength": "2级", /*当前风力*/
"humidity": "4%", /*当前湿度*/
"time": "14:25" /*更新时间*/
},
"today": {
"city": "天津",
"date_y": "2014年03月21日",
"week": "星期五",
"temperature": "8℃~20℃", /*今日温度*/
"weather": "晴转霾", /*今日天气*/
"weather_id": { /*天气唯一标识*/
"fa": "00", /*天气标识00:晴*/
"fb": "53" /*天气标识53:霾 如果fa不等于fb,说明是组合天气*/
},
"wind": "西南风微风",
"dressing_index": "较冷", /*穿衣指数*/
"dressing_advice": "建议着大衣、呢外套加毛衣、卫衣等服装。", /*穿衣建议*/
"uv_index": "中等", /*紫外线强度*/
"comfort_index": "",/*舒适度指数*/
"wash_index": "较适宜", /*洗车指数*/
"travel_index": "适宜", /*旅游指数*/
"exercise_index": "较适宜", /*晨练指数*/
"drying_index": ""/*干燥指数*/
},
"future": [ /*未来几天天气*/
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "南风3-4级",
"week": "星期一",
"date": "20140804"
},
{
"temperature": "28℃~36℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期二",
"date": "20140805"
},
{
"temperature": "27℃~35℃",
"weather": "晴转多云",
"weather_id": {
"fa": "00",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期三",
"date": "20140806"
},
{
"temperature": "27℃~34℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东南风3-4级",
"week": "星期四",
"date": "20140807"
},
{
"temperature": "27℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "东北风4-5级",
"week": "星期五",
"date": "20140808"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期六",
"date": "20140809"
},
{
"temperature": "26℃~33℃",
"weather": "多云",
"weather_id": {
"fa": "01",
"fb": "01"
},
"wind": "北风4-5级",
"week": "星期日",
"date": "20140810"
}
]
},
"error_code": 0
}
清除格式化代码生成C#类
C#类代码选中代码

代码

<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.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对象的属性,根据属性值的类型生成对应的类名即可, 这里不做详细介绍了。 代码写的有点丑,希望大家用得着。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: