最近的項目中需要和一個服務端程序通訊,而通訊的協議是基于流行的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對象的屬性,根據屬性值的類型生成對應的類名即可, 這里不做詳細介紹了。 代碼寫的有點丑,希望大家用得著。
新聞熱點
疑難解答