Describes the conversion between XML and JSON.

Source: Internet
Author: User
JSON: JavaScript Object Notation (JavaScriptObjectNotation ). JSON is the syntax for storing and exchanging text information. Similar to XML. JSON is smaller, faster, and easier to parse than XML.

About JOSN

The first article in this series has simply compared XML and JSON time frames.

JSON: JavaScript Object Notation (JavaScript Object Notation ). JSON is the syntax for storing and exchanging text information. Similar to XML. JSON is smaller, faster, and easier to parse than XML.

What is JSON?

JSON refers to the JavaScript Object Notation (JavaScript Object Notation). JSON is a lightweight text data exchange format. JSON is independent of the language. * JSON is self-descriptive and easier to understand.

JSON uses JavaScript syntax to describe data objects, but JSON is still independent of the language and platform. The JSON parser and JSON library support many different programming languages.

JSON format

Although there are many ideas about how XML has the cross-platform and cross-language advantages, unless it is applied to Web Services, in common Web applications, developers often use their brains for XML parsing. whether the server generates or processes XML, or the client uses JavaScript to parse XML, it often leads to complicated code and extremely low development efficiency. In fact, for most Web applications, they do not need complicated XML to transmit data at all, and XML scalability is rarely advantageous. many AJAX applications even directly return HTML fragments to build dynamic Web pages. Compared with returning XML and parsing it, returning HTML fragments greatly reduces the complexity of the system, but at the same time lacks some flexibility.

XML2JOSN

Third-party class library conversion

string xml = @"
  
  
   
    
     Alan
    
    
     http://www.google.com</url>
    
   
   
    
     Louis
    
    
     http://www.yahoo.com</url>
    
   
  "; 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"//      }//    ]//  }//}

System. Web. Extensions library file reference

  var xml =                   @"
            
   
    True
             
   
    Hello World
             
   
    999
           
  ";            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);

2. manually write the conversion class

  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   into "aa":null                //          xx 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();        }    }

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");// 
  // 
  
   //   
   
    //     
    
     Alan
    //     
    
     http://www.google.com</url>//   
    
   //   
   
    //     
    
     Louis
    //     
    
     http://www.yahoo.com</url>//   
    
   // 
  

Other conversion methods

The preceding section details the conversion between XML and JSON (text and text). For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.