JOSN简介
在本系列的第一篇已简朴比较了XML和JSON 时间机
JSON:JavaScript 对象示意法(JavaScript Object Notation)。 JSON 是存储和交流文本信息的语法。相似 XML。 JSON 比 XML 更小、更快,更容易剖析。
什么是 JSON?
JSON 指的是 JavaScript 对象示意法(JavaScript Object Notation) JSON 是轻量级的文本数据交流花样 JSON 独立于言语 * JSON 具有自我形貌性,更容易明白
JSON 运用 JavaScript 语法来形貌数据对象,然则 JSON 依然独立于言语和平台。JSON 剖析器和 JSON 库支撑很多差别的编程言语。
JSON花样化
只管有很多宣扬关于 XML 怎样具有跨平台,跨言语的上风,但是,除非运用于 Web Services,不然,在一般的 Web 运用中,开辟者经常为 XML 的剖析伤透了头脑,无论是服务器端生成或处置惩罚 XML,照样客户端用 JavaScript 剖析 XML,都经常致使庞杂的代码,极低的开辟效力。实际上,关于大多数 Web 运用来讲,他们基础不须要庞杂的 XML 来传输数据,XML 的扩展性很少具有上风,很多 AJAX 运用以至直接返回 HTML 片断来构建动态 Web 页面。和返回 XML 并剖析它比拟,返回 HTML 片断大大降低了体系的庞杂性,但同时缺少了肯定的灵活性
XML2JOSN
借助第三方类库转换
运用NuGet增加第三方类库
<code>string xml = @"<?xml version='1.0' standalone='no'?> <root> <person id='1'> <name>Alan</name> <url>http://www.google.com</url> </person> <person id='2'> <name>Louis</name> <url>http://www.yahoo.com</url> </person> </root>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string jsonText = JsonConvert.SerializeXmlNode(doc); //{ // "?xml": { // "@version": "1.0", // "@standalone": "no" // }, // "root": { // "person": [ // { // "@id": "1", // "name": "Alan", // "url": "http://www.google.com" // }, // { // "@id": "2", // "name": "Louis", // "url": "http://www.yahoo.com" // } // ] // } //}</code>
关于每一个表标签的属性对应JSON中的"@"标署名
假如有多个同名标签就会增加到一个数组鸠合中
其他体式格局转换
1.运用.NET Framework中的JavaScriptSerializer类
起首须要确保你的工程或服务器支撑.NET 4.0或以上版本的Framework,不然没法找到该类。
经由过程JavaScriptSerializer来完成。它的名字空间为:System.Web.Script.Serialization
假如要运用它,还须增加
System.Web.Extensions库文件援用
<code> var xml = @"<Columns> <Column Name=""key1"" DataType=""Boolean"">True</Column> <Column Name=""key2"" DataType=""String"">Hello World</Column> <Column Name=""key3"" DataType=""Integer"">999</Column> </Columns>"; var dic = XDocument .Parse(xml) .Descendants("Column") .ToDictionary( c => c.Attribute("Name").Value, c => c.Value ); var json = new JavaScriptSerializer().Serialize(dic); Console.WriteLine(json);</code>
2.手动编写转换类
<code> public class Xml2JSON { public static string XmlToJSON(XmlDocument xmlDoc) { StringBuilder sbJSON = new StringBuilder(); sbJSON.Append("{ "); XmlToJSONnode(sbJSON, xmlDoc.DocumentElement, true); sbJSON.Append("}"); return sbJSON.ToString(); } // XmlToJSONnode: Output an XmlElement, possibly as part of a higher array private static void XmlToJSONnode(StringBuilder sbJSON, XmlElement node, bool showNodeName) { if (showNodeName) sbJSON.Append("\"" + SafeJSON(node.Name) + "\": "); sbJSON.Append("{"); // Build a sorted list of key-value pairs // where key is case-sensitive nodeName // value is an ArrayList of string or XmlElement // so that we know whether the nodeName is an array or not. SortedList childNodeNames = new SortedList(); // Add in all node attributes if (node.Attributes != null) foreach (XmlAttribute attr in node.Attributes) StoreChildNode(childNodeNames, attr.Name, attr.InnerText); // Add in all nodes foreach (XmlNode cnode in node.ChildNodes) { if (cnode is XmlText) StoreChildNode(childNodeNames, "value", cnode.InnerText); else if (cnode is XmlElement) StoreChildNode(childNodeNames, cnode.Name, cnode); } // Now output all stored info foreach (string childname in childNodeNames.Keys) { ArrayList alChild = (ArrayList)childNodeNames[childname]; if (alChild.Count == 1) OutputNode(childname, alChild[0], sbJSON, true); else { sbJSON.Append(" \"" + SafeJSON(childname) + "\": [ "); foreach (object Child in alChild) OutputNode(childname, Child, sbJSON, false); sbJSON.Remove(sbJSON.Length - 2, 2); sbJSON.Append(" ], "); } } sbJSON.Remove(sbJSON.Length - 2, 2); sbJSON.Append(" }"); } // StoreChildNode: Store data associated with each nodeName // so that we know whether the nodeName is an array or not. private static void StoreChildNode(SortedList childNodeNames, string nodeName, object nodeValue) { // Pre-process contraction of XmlElement-s if (nodeValue is XmlElement) { // Convert <aa></aa> into "aa":null // <aa>xx</aa> into "aa":"xx" XmlNode cnode = (XmlNode)nodeValue; if (cnode.Attributes.Count == 0) { XmlNodeList children = cnode.ChildNodes; if (children.Count == 0) nodeValue = null; else if (children.Count == 1 && (children[0] is XmlText)) nodeValue = ((XmlText)(children[0])).InnerText; } } // Add nodeValue to ArrayList associated with each nodeName // If nodeName doesn't exist then add it object oValuesAL = childNodeNames[nodeName]; ArrayList ValuesAL; if (oValuesAL == null) { ValuesAL = new ArrayList(); childNodeNames[nodeName] = ValuesAL; } else ValuesAL = (ArrayList)oValuesAL; ValuesAL.Add(nodeValue); } private static void OutputNode(string childname, object alChild, StringBuilder sbJSON, bool showNodeName) { if (alChild == null) { if (showNodeName) sbJSON.Append("\"" + SafeJSON(childname) + "\": "); sbJSON.Append("null"); } else if (alChild is string) { if (showNodeName) sbJSON.Append("\"" + SafeJSON(childname) + "\": "); string sChild = (string)alChild; sChild = sChild.Trim(); sbJSON.Append("\"" + SafeJSON(sChild) + "\""); } else XmlToJSONnode(sbJSON, (XmlElement)alChild, showNodeName); sbJSON.Append(", "); } // Make a string safe for JSON private static string SafeJSON(string sIn) { StringBuilder sbOut = new StringBuilder(sIn.Length); foreach (char ch in sIn) { if (Char.IsControl(ch) || ch == '\'') { int ich = (int)ch; sbOut.Append(@"\u" + ich.ToString("x4")); continue; } else if (ch == '\"' || ch == '\\' || ch == '/') { sbOut.Append('\\'); } sbOut.Append(ch); } return sbOut.ToString(); } }</code>
JOSN2XML
借助第三方类库转换
<code>string json = @"{ '?xml': { '@version': '1.0', '@standalone': 'no' }, 'root': { 'person': [ { '@id': '1', 'name': 'Alan', 'url': 'http://www.google.com' }, { '@id': '2', 'name': 'Louis', 'url': 'http://www.yahoo.com' } ] } }"; XmlDocument doc = JsonConvert.DeserializeXmlNode(json); doc.Save(@"D:\json.xml"); // <?xml version="1.0" standalone="no"?> // <root> // <person id="1"> // <name>Alan</name> // <url>http://www.google.com</url> // </person> // <person id="2"> // <name>Louis</name> // <url>http://www.yahoo.com</url> // </person> // </root></code>
其他体式格局转换
以上就是细致引见XML与JSON互相转换(图文)的细致内容,更多请关注ki4网别的相干文章!