Json字符串、Xml字符串转C#实体类Class
在项目开发过程中,经常需要和不同部门或者不同的组员一起协同工作,但对方写的返回json格式的结果集,我们需要用这些数据,那么如何来生成对应的类代码和实体对象呢?
对于是使用Swagger框架的,网上都有现成的生成工具,这里就不说了。
对于原生的json字符串或xml字符串呢?于是参考了网上的做法,一个偶然的机会,在一个网站上看到的,可以把json字符串,转成C#对应的实体类,参考:http://www.bejson.com/convert/json2csharp/
根据网上的,自己稍微修改了一点,使用Html做一个简单的字符串转实体类的功能,仅仅实现基本的,可以直接把Json字符串转成C#对应的实体类,更符合自己的使用,记录如下:
其中使用了jquery-2.2.0.min.js,我这里就不贴了,自己到网上去下载一个。
这里是Html的代码:保存到JsonXmlToClass.html文件中:
<!DOCTYPE html> <html> <head> <title>JSON字符串转C#实体类</title> </head> <body> <div class="panel panel-default"> <div class="panel-heading"> <div class="media"> <div class="media-body"> <h4 class="media-heading">JSON字符串转C#实体类</h4> </div> </div> </div> <div class="panel-body"> <!--内容块开始--> <p style="margin-top: 20px;"> 命名空间:<input type="text" id=txtNameSpace /><br /> <textarea id="json" class="form-control" style="height: 200px; width:800px;"></textarea> </p> <p> <button type="submit" class="btn btn-primary btn-sm" onclick="return testJsonCase();">来个json试试</button> <button type="submit" data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-sm" onclick="genJson();">Json生成实体类</button> <button type="button" class="btn btn-danger btn-sm" onclick="$('#json').val(''),$('#resData').val('')">清空</button> <button type="button" class="btn btn-danger btn-sm" onclick="genJsonTest('#json')">testJson</button> <button type="submit" class="btn btn-primary btn-sm" onclick="return testXmlCase();">来个xml试试</button> <button type="submit" data-toggle="modal" data-target="#myModal" class="btn btn-primary btn-sm" onclick="genXml();">Xml生成实体类</button> <button type="button" class="btn btn-danger btn-sm" onclick="$('#json').val(''),$('#resData').val('')">清空</button> </p> <p style="margin-top: 20px;"><textarea id="resData" class="form-control" style="height: 300px; width:800px;"></textarea></p> <!-- Modal --> <!--内容块结束--> </div> <div class="panel-footer"></div> </div> <hr /> <input id="btnTest" onclick="t1(22)" type="button" value="测试运行时代码" /> <br /> <textarea title="js" style="height: 60px; width:800px;"> function t1(v){ console.log(new Date().getSeconds() + "----------执行日志-----------" + v); } </textarea> <hr /> </body> </html> <!--script src="jquery-1.10.2.js"></script--> <script src="jquery-2.2.0.min.js"></script> <script src="jsontocsharp.js"></script> <script src="XmlTocsharp.js"></script> <script> //document.title = Math.random(); //$(function(){console.log("init "+new Date().getSeconds());}); $(function () { console.log("init start " + new Date().getSeconds()); $('textarea[title]').each(function () { //return (new Function("return "+""+($(this).text()+""))(); window.eval(' ' + $(this).text() + ' '); }); console.log("init end " + new Date().getSeconds()); }); </script> <script> function genJsonTest(obj) { alert($(obj).val()); } function genJson() { $("#resData").html(''); if ($("#json").val().trim() == "") { $("#resData").text("请填写JSON"); return false; } try { var v = eval("(" + document.getElementById("json").value + ")"); } catch (e) { $("#resData").html('Json字符串转换失败!\r\n请检查字符串是否为标准json格式。'); return false; } JSON2CSharp.NamespaceConfig = { IsGenNamespace: false, Namespace: document.getElementById("txtNameSpace").value }; //JSON2CSharp.NamespaceConfig.IsGenNamespace = false; var res = JSON2CSharp.convert(v); $("#resData").val($("<div/>").html(res).text()); }; // 加载xml文档 function loadXmlFile(xmlFile) { var xmlDoc = null; if (window.ActiveXObject) { xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = false; xmlDoc.load(xmlFile); } else if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument('', 'doc', null); xmlDoc.async = false; xmlDoc.preserveWhiteSpace = true; xmlDoc.load(xmlFile); } else if (window.XMLHttpRequest) {//支持出网络获取 var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET", "#", false); xmlhttp.send(null); xmlDoc = xmlhttp.responseXML.documentElement; } return xmlDoc; } //加载xml字符串 function loadXmlStr(xmlStr) { var xmlDoc = null; if (window.DOMParser) { //非IE浏览器 xmlDoc = (new DOMParser()).parseFromString(xmlStr, "text/xml"); } else { //IE浏览器 xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); // 或者:xmlDoc = new ActiveXObject("MSXML2.DOMDocument"); xmlDoc.async = "false"; //不启用异步,保证加载文件成功之前不会进行下面操作 xmlDoc.loadXML(xmlStr); } return xmlDoc; } function genXml() { $("#resData").html(''); if ($("#json").val().trim() == "") { $("#resData").text("请填写Xml"); return false; } try { var d = loadXmlStr(document.getElementById("json").value); if (d == null) { $("#resData").html('loadXml字符串转换失败!\r\n请检查字符串是否为标准xml格式。'); return false; } } catch (e) { $("#resData").html('loadXml字符串转换失败!\r\n请检查字符串是否为标准xml格式。\r\n' + e.message); return false; } Xml2CSharp.NamespaceConfig = { IsGenNamespace: false, Namespace: document.getElementById("txtNameSpace").value }; //JSON2CSharp.NamespaceConfig.IsGenNamespace = false; var res = Xml2CSharp.convert(d); $("#resData").val($("<div/>").html(res).text()); } function testJsonCase() { $("#json").val('{\r\n\t"animals":{\r\n\t"dog":[\r\n\t\t{"name":"Rufus","breed":"labrador","count":1,"twoFeet":false},\r\n\t\t{"name":"Marty","breed":"whippet","count":1,"twoFeet":false}\r\n\t],\r\n\t"cat":{"name":"Matilda"}\r\n}\r\n}'); } function testXmlCase() { var xml = ""; xml += "<?xml version='1.0' encoding='utf-16'?>\r\n"; xml += "<testRoot xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>\r\n"; xml += " <dataHead id='1'>\r\n"; xml += " <jkid>23270000</jkid>\r\n"; //xml += " <jkname>BD11F82096F0290DB2866BD266A0CEDF</jkname>\r\n"; xml += " </dataHead>\r\n"; xml += " <dataBody id='2'>\r\n"; xml += " <vehispara xsi:type='JCZ01'>\r\n"; xml += " <tsno>23270002</tsno>\r\n"; //xml += " <orgcode>23270002</orgcode>\r\n"; xml += " <station>XXXX有限公司</station>\r\n"; xml += " <linkdate>2038-08-11T00:00:00</linkdate>\r\n"; xml += " <testAdd />\r\n"; xml += " <status>1</status>\r\n"; xml += " <lng xsi:nil='true' />\r\n"; xml += " </vehispara>\r\n"; xml += " </dataBody>\r\n"; xml += "</testRoot>\r\n"; $("#json").val(xml); } </script>
代码很简单,我想你一定会,注意里面引用了jQuery文件;另外jsontocsharp.js文件如下
这个是JsonTocsharp.js文件,在生成的代码时也可以生成命名空间的代码,并且可配置的哦!内容如下:
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: [], NamespaceConfig: { IsGenNamespace: true, Namespace: "JsonNamespace.TestWeb" }, _genClassCode: function (obj, name) { var clas = this._genComment(name || "RootObj", obj).replace(/\t/g, ""); clas += "public partial class {0}\r\n{\r\n".format(name || "RootObj"); for (var n in obj) { var v = obj[n]; n = n.trim(); n = n.substring(0, 1).toUpperCase() + n.substring(1); if (n.length > 0) clas += "{0}\tpublic {1} {2} { get; set; }\r\n\r\n".format(this._genComment(n, v), this._genTypeByProp(n, v), n); } clas += "}\r\n"; if (this._allClass.indexOf(clas) < 0) this._allClass.push(clas); this._allClass.sort(); return this._allClass.join("\r\n"); }, _genTypeByProp: function (name, val) { switch (Object.prototype.toString.apply(val)) { case "[object Number]": { return val.toString().indexOf(".") > -1 ? "double" : "int"; } case "[object Boolean]": { return "bool"; } 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 (obj, val) { //return ""; var commm = typeof (val) == "string" && /.*[\u4e00-\u9fa5]+.*$/.test(val) ? val : obj; commm += Object.prototype.toString.apply(val) == "[object Array]" ? "List" : ""; return "\t/// <summary>\r\n\t/// " + commm + "\r\n\t/// </summary>\r\n"; }, _genNamespase: function (objClass) { var tmpClass = ""; if (this.NamespaceConfig.IsGenNamespace) tmpClass = this._genComment("本命名空间下的代码使用Jack自动生成的代码\r\n/// 如果你修改了本次生成的代码,则后续将有可能会被覆盖或重置").replace(/\t/g, "") + "namespace " + this.NamespaceConfig.Namespace + "\r\n{\r\n" + objClass + "}\r\n"; else tmpClass = objClass; return tmpClass; }, convert: function (jsonObj) { this._allClass = []; return this._genNamespase(this._genClassCode(jsonObj)); } }
这个是XmlTocsharp.js文件,内容如下:
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, ""); } Xml2CSharp = { _allClass: {}, NamespaceConfig: { IsGenNamespace: true, Namespace: "XmlNamespace.TestWeb" }, _genClassCode: function (obj, name) { var _ClassAtt = []; var attReplace = {}; name = name || obj.nodeName; var clsAtt = "[System.SerializableAttribute()]\r\n[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]\r\n"; var cls = ""; var clsCommen = this._genComment(name, obj).replace(/\t/g, ""); cls += "public partial class {0}\r\n{\r\n".format(name); var attKey = obj.getAttributeNames(); for (var j = 0; j < attKey.length; j++) { n = attKey[j].trim(); var att = obj.getAttributeNode(attKey[j]); var elmAtt = "\t[System.Xml.Serialization.XmlAttribute(AttributeName = \"" + n + "\")]\r\n"; if (n.indexOf("xmlns:") >= 0)//过滤xmlns:xsi、xmlns:xsd等这一类的属性 continue; if (n == "xsi:type") { clsAtt += "[System.Xml.Serialization.XmlInclude(typeof ({0}))]\r\n".format(obj.attributes[n].value); var tmpCls = this._genComment(obj.attributes[n].value, obj).replace(/\t/g, ""); tmpCls += "[System.SerializableAttribute()]\r\n"; tmpCls += "public partial class {0}:{1}{}\r\n".format(obj.attributes[n].value, name); this._allClass.push(tmpCls); //continue; n = n.split(":")[1]; elmAtt = "\t[System.Xml.Serialization.XmlAttribute(AttributeName = \"" + n + "\", Namespace = \"http://www.w3.org/2001/XMLSchema-instance\")]\r\n"; } var tArr = "{0}\tpublic {1} {2} { get; set; }\r\n\r\n".format(this._genComment(n, att) + elmAtt, this._genTypeByProp(n, att), n); var arrIndex = _ClassAtt.indexOf(tArr); if (arrIndex < 0) { _ClassAtt.push(tArr); } else { attReplace[arrIndex] = "{0}\tpublic {1} {2} { get; set; }\r\n\r\n".format(this._genComment(n, att), this._genTypeByProp([n], [att]), n + "List"); } } for (var i = 0; i < obj.children.length; i++) { var v = obj.children[i]; var n = v.nodeName; if (n.length > 0) { var elmAtt = "\t[System.Xml.Serialization.XmlElement(ElementName = \"" + n + "\", IsNullable = true)]\r\n"; var tChildArr = "{0}\tpublic {1} {2} { get; set; }\r\n\r\n".format(this._genComment(n, v) + elmAtt, this._genTypeByProp(n, v), n); var arrIndex = _ClassAtt.indexOf(tChildArr); if (arrIndex < 0) { _ClassAtt.push(tChildArr); } else { attReplace[arrIndex] = "{0}\tpublic {1} {2} { get; set; }\r\n\r\n".format(this._genComment(n, v) + elmAtt, this._genTypeByProp([n], [v]), n + "List"); } } } for (var key in attReplace) { _ClassAtt[key] = attReplace[key]; } _ClassAtt.sort(); cls = clsCommen + clsAtt + cls + _ClassAtt.join("\r\n"); cls += "}\r\n"; //if (this._allClass.indexOf(cls) < 0) // this._allClass.push(cls); //this._allClass.sort(); //return this._allClass.join("\r\n"); if (Object.keys(this._allClass).indexOf(name) < 0) this._allClass[name] = cls; else { if (this._allClass[name].length < cls.length) this._allClass[name] = cls; } }, _genTypeByProp: function (val, obj) { var t1 = obj.childElementCount > 0 ? obj : val; var t = Object.prototype.toString.apply(t1); var child = obj.children; switch (t) { case "[object Number]": { return obj.toString().indexOf(".") > -1 ? "double" : "int"; } case "[object Boolean]": { return "bool"; } case "[object Date]": { return "DateTime"; } case "[object Object]": case "[object Element]": case "[object HTMLUnknownElement]": { val = "{0}".format(val); //val = val.substring(0, 1).toUpperCase() + val.substring(1); this._genClassCode(obj, val); return val; } case "[object Array]": { val = "{0}".format(val); //val = val.firstUpperCase(); var t = "List <{0}>".format(val); return t; } default: { return "string"; } } }, _genComment: function (obj, val) { //return ""; var commm = typeof (val) == "string" && /.*[\u4e00-\u9fa5]+.*$/.test(val) ? val : obj; commm += Object.prototype.toString.apply(val) == "[object Array]" ? "List" : ""; return "\t/// <summary>\r\n\t/// " + commm + "\r\n\t/// </summary>\r\n"; }, _genNamespase: function (objClass) { var tmpClass = ""; if (this.NamespaceConfig.IsGenNamespace) tmpClass = this._genComment("本命名空间下的代码使用Jack自动生成的代码\r\n/// 如果你修改了本次生成的代码,则后续将有可能会被覆盖或重置").replace(/\t/g, "") + "namespace " + this.NamespaceConfig.Namespace + "\r\n{\r\n" + objClass + "}\r\n"; else tmpClass = objClass; return tmpClass; }, convert: function (xmlDom) { this._allClass = {}; this._genClassCode(xmlDom.firstChild); var allClass = Object.values(this._allClass).join("\r\n"); return this._genNamespase(allClass); } }
生成完了代码,那么怎么用呢?只要把json返回的结果集字符串,转换成对应类生成的对象类就可以了,写几个示例参考如下:
private void button1_Click(object sender, EventArgs e) { string xml1 = @"<?xml version='1.0' encoding='utf-16'?> <testRoot xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <dataHead id='1'> <jkid>23270000</jkid> </dataHead> <dataBody id='2'> <vehispara xsi:type='veh'> <tsno>23270002</tsno> <station>XXXX有限公司</station> <linkdate>2038-08-11T00:00:00</linkdate> <testAdd /> <status>1</status> <lng xsi:nil='true' /> </vehispara> </dataBody> </testRoot> "; var xmlObj = Lib.Xml.XmlHelper.XmlDeSerializer<xmlMod.xml1.testRoot>(xml1); showMsg(xmlObj != null ? "testRoot字符串转换对象成功" : "testRoot字符串转换对象失败"); //xmlObj.dataBody.vehispara.status = null; xmlObj.dataBody.vehispara.type = null; string xmlStr = Xml.XmlHelper.XmlSerialize<xmlMod.xml1.testRoot>(xmlObj); xmlObj = Lib.Xml.XmlHelper.XmlDeSerializer<xmlMod.xml1.testRoot>(xmlStr); showMsg(string.IsNullOrEmpty(xmlStr) ? "testRoot对象转换字符串失败" : "testRoot对象转换字符串成功"); xmlObj = new xmlMod.xml1.testRoot(); xmlObj.dataBody = new xmlMod.xml1.dataBody(); xmlObj.dataHead = new xmlMod.xml1.dataHead(); xmlObj.dataBody.vehispara = new xmlMod.xml1.vehispara(); xmlObj.dataHead.id = "44"; //xmlObj.dataBody.vehispara.type = "vvv"; var _xmlStr = Xml.XmlHelper.XmlSerialize<xmlMod.xml1.testRoot>(xmlObj); showMsg(string.IsNullOrEmpty(xmlStr) ? "新testRoot对象转换字符串失败\r\n" : "新testRoot对象转换字符串成功\r\n"); string xml2 = @"<?xml version='1.0' encoding='utf-8' ?> <books ISBN='9787544238212'> <book id='1'> <title>xml学习笔记</title> <price>30</price> <pagecount>300</pagecount> </book> <book id='4'> <title>xml学习笔记</title> <price>30</price> <pagecount>300</pagecount> </book> </books> "; var obj = Lib.Xml.XmlHelper.XmlDeSerializer<xmlMod.xml2.books>(xml2); showMsg(obj != null ? "books字符串转换对象成功" : "books字符串转换对象失败"); xmlMod.xml2.books bs = new xmlMod.xml2.books(); bs.ISBN = "sn1234"; bs.bookList = new List<xmlMod.xml2.book>(); bs.bookList.Add(new xmlMod.xml2.book()); bs.bookList[0].pagecount = "1"; bs.bookList.Add(new xmlMod.xml2.book()); bs.bookList[1].id = "423"; bs.bookList[1].pagecount = "2"; string strBooks = Lib.Xml.XmlHelper.XmlSerialize<xmlMod.xml2.books>(bs); showMsg(string.IsNullOrEmpty(strBooks) ? "新books对象转换字符串失败" : "新books对象转换字符串成功"); var obj1 = Lib.Xml.XmlHelper.XmlDeSerializer<xmlMod.xml2.books>(strBooks); showMsg(string.IsNullOrEmpty(strBooks) ? "原始字符串books对象转换字符串失败" : "原始字符串books对象转换字符串成功"); string xml3 = @"<?xml version='1.0'?> <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <Person> <Name>小小</Name> <Age>21</Age> <Books> <Book> <Title>C语言</Title> <ISBN>SOD1S</ISBN> </Book> </Books> </Person> <Person> <Name>小莫</Name> <Age>23</Age> <Books> <Book> <Title>马列主义</Title> <ISBN>SOD1323DS</ISBN> </Book> <Book> <Title>C#</Title> <ISBN>SOD1S</ISBN> </Book> </Books> </Person> <Person> <Name>小红</Name> <Age>22</Age> <Books> <Book> <Title>思想</Title> <ISBN>SID1323DSD</ISBN> </Book> <Book> <Title>Jsp</Title> <ISBN>SOD1S</ISBN> </Book> <Book> <Title>ASP</Title> <ISBN>SOD1S</ISBN> </Book> </Books> </Person> </root> "; var RootObj = Lib.Xml.XmlHelper.XmlDeSerializer<xmlMod.xml3.root>(xml3); showMsg(RootObj != null ? "root字符串转换对象成功" : "root字符串转换对象失败"); string strRootObj = Lib.Xml.XmlHelper.XmlSerialize<xmlMod.xml3.root>(RootObj); showMsg(string.IsNullOrEmpty(strRootObj) ? "root对象转换字符串失败" : "root对象转换字符串成功"); }
剩下的就看你怎么使用rootObj对象了,你需要的属性和数据都在里面。
参考出处:http://www.bejson.com/convert/json2csharp/
关注我】。(●'◡'●)
如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的【因为,我的写作热情也离不开您的肯定与支持,感谢您的阅读,我是【Jack_孟】!
本文来自博客园,作者:jack_Meng,转载请注明原文链接:https://www.cnblogs.com/mq0036/p/10240043.html
【免责声明】本文来自源于网络,如涉及版权或侵权问题,请及时联系我们,我们将第一时间删除或更改!
posted on 2019-01-08 17:08 jack_Meng 阅读(3808) 评论(0) 编辑 收藏 举报