Json.NET: convert JSON string to XML or XML to JSON string

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to XML format and viceversa?

Convert JSON String to XML string

I have a JSON string as : var jsonString = JSON.stringify(dataObject); document.getElementById(hdnChromedata).value = jsonString; ==> hdnChromedata = JSON string BUT in a different code section

JSON string to XML string

I want to know how can I convert JSON string to XML string in ASP.NET 1.1 I can not use third party library for some restriction. Any suggestion would be a big help.

convert json string to xml string in iphone [closed]

I have json string came from my web service, which I stored to nsdictionary object. Now I want to convert this in xml string. anyone have idea how can I perform this without using any external library

Use JavaScriptSerializer to convert Json to Xml

How to convert json string to xml using JavaScriptSerializer?

Tool (javascript) to convert a XML string to JSON [closed]

What is the best javascript function/plugin/library to convert a XML string to JSON. I found that tool : http://www.thomasfrank.se/xml_to_json.html, but it does not like strings starting with 0. i.e.

Can not convert attribut “type” in xml string to json string by Restlet StringRepresentation class

I used StringRepresentation java class in Restlet to convert a xml string to json string. There’s a type attribute in my xml string, for example: <contacts> <contact index=0 type=type1

Convert Json to XML String with namespace?

I have a json string like this { RSS: { Channel: { item: [ { title: Overlay HD/CC, guid: 1, description: This example shows tooltip overlays for captions and quality., jwplayer:ima

Check if string either contains xml or json data

I receive a String which contains either xml or json contents. If String contains json content I use jackson(java api) to Convert JSON to Java object And if it contains xml contents I use JAXB to Con

Is it possible to convert an XML string into JSON in Cold Fusion 8

I’m in a situation, where i receive a query containing XML string. I’m supposed to convert it to json. I wrote a small CF Function, that traverses/parse through the XML and conveniently transforms it

JSON, XML or String concatenation

I am doing a new application where I want to choose which protocol to use in it. I tried the String concatenation and the XML before, but never tried the JSON Object. Well Which one of those three is

Answers

Yes. Using the JsonConvert class which contains helper methods for this precise purpose:

// To convert an XML node contained in string xml into a JSON string   
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

Documentation here: Converting between JSON and XML with Json.NET

I’m not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) — there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations.

But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both.

Thanks for David Brown’s answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:

XmlNote myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString);
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);

Here is a blog that tells about conversion of XML to JSON and JSON to XML: http://sandeep-aparajit.blogspot.com/2010/01/json-to-xml-and-xml-to-json-converter.html

Try this function. I just wrote it and haven’t had much of a chance to test it, but my preliminary tests are promising.

public static XmlDocument JsonToXml(string json)
    {
        XmlNode newNode = null;
        XmlNode appendToNode = null;
        XmlDocument returnXmlDoc = new XmlDocument();
        returnXmlDoc.LoadXml("<Document />");
        XmlNode rootNode = returnXmlDoc.SelectSingleNode("Document");
        appendToNode = rootNode;

        string[] arrElementData;
        string[] arrElements = json.Split('/r');
        foreach (string element in arrElements)
        {
            string processElement = element.Replace("/r", "").Replace("/n", "").Replace("/t", "").Trim();
            if ((processElement.IndexOf("}") > -1 || processElement.IndexOf("]") > -1) &&
                appendToNode != rootNode)
            {
                appendToNode = appendToNode.ParentNode;
            }
            else if (processElement.IndexOf("[") > -1)
            {
                processElement = processElement.Replace(":", "").Replace("[", "").Replace("/"", "").Trim();
                newNode = returnXmlDoc.CreateElement(processElement);
                appendToNode.AppendChild(newNode);
                appendToNode = newNode;
            }
            else if (processElement.IndexOf("{") > -1 && processElement.IndexOf(":") > -1)
            {
                processElement = processElement.Replace(":", "").Replace("{", "").Replace("/"", "").Trim();
                newNode = returnXmlDoc.CreateElement(processElement);
                appendToNode.AppendChild(newNode);
                appendToNode = newNode;
            }
            else
            {
                if (processElement.IndexOf(":") > -1)
                {
                    arrElementData = processElement.Replace(": /"", ":").Replace("/",", "").Replace("/"", "").Split(':');
                    newNode = returnXmlDoc.CreateElement(arrElementData[0]);
                    for (int i = 1; i < arrElementData.Length; i++)
                    { newNode.InnerText += arrElementData[i]; }
                    appendToNode.AppendChild(newNode);
                }
            }
        }

        return returnXmlDoc;
    }

mmhhh… I found some problems in this code, if for example the document didn’t have any line feed, the code could not work (I have to convert a “only one line json document”). Also, it was changing a lot of my data (I have : and ” in the data values). But it was a very good start for me to implement the procedure. I publish it, just:

  1. It is written in vb.net, not c# sorry
  2. It is not optimized, it is written in a “safe” and “debug-friendly” way

    Private Function JsonToXml(ByVal json As String) As XmlDocument
    Dim newNode As XmlNode = Nothing
    Dim appendToNode As XmlNode = Nothing
    Dim returnXmlDoc As XmlDocument = New XmlDocument
    returnXmlDoc.LoadXml("<Document />")
    Dim rootNode As XmlNode = returnXmlDoc.SelectSingleNode("Document")
    appendToNode = rootNode
    
    json = json.Replace(",", "," & vbLf)
    json = json.Replace("{", "{" & vbLf)
    json = json.Replace("}", vbLf & "}" & vbLf)
    json = json.Replace("[", "[" & vbLf)
    json = json.Replace("]", vbLf & "]" & vbLf)
    
    Dim arrElementData() As String
    Dim arrElements() As String = json.Split(vbLf)
    For Each element As String In arrElements
        Dim processElement As String = element.Replace(vbLf, "").Replace(vbCr, "").Replace(vbTab, "").Trim()
        If processElement.Trim <> "" Then
            If (processElement.IndexOf("}") > -1 Or processElement.IndexOf("]") > -1) And Not (appendToNode Is rootNode) Then
                appendToNode = appendToNode.ParentNode
            ElseIf (processElement.IndexOf("[") > -1) Then
                processElement = processElement.Replace(":", "").Replace("[", "").Replace("""", "").Trim()
                If processElement.Trim = "" Then
                    processElement = "Square"
                End If
                newNode = returnXmlDoc.CreateElement(processElement)
                appendToNode.AppendChild(newNode)
                appendToNode = newNode
            ElseIf (processElement.IndexOf("{") > -1) Then
                processElement = processElement.Replace(":", "").Replace("{", "").Replace("""", "").Trim()
                If processElement.Trim = "" Then
                    processElement = "Element"
                End If
                newNode = returnXmlDoc.CreateElement(processElement)
                appendToNode.AppendChild(newNode)
                appendToNode = newNode
            Else
                Dim FoundAt As Integer = processElement.IndexOf(":")
                If (FoundAt > -1) Then
                    Dim NodeName As String = processElement.Substring(0, FoundAt - 1).Replace("""", "")
                    Dim NodeValue As String = processElement.Substring(FoundAt + 1, processElement.Length - FoundAt - 1).Trim
                    If NodeValue.StartsWith("""") Then
                        NodeValue = NodeValue.Substring(1, NodeValue.Length - 1).Trim
                    End If
                    If NodeValue.EndsWith(",") Then
                        NodeValue = NodeValue.Substring(0, NodeValue.Length - 1).Trim
                    End If
                    If NodeValue.EndsWith("""") Then
                        NodeValue = NodeValue.Substring(0, NodeValue.Length - 1).Trim
                    End If
                    newNode = returnXmlDoc.CreateElement(NodeName)
                    newNode.InnerText = NodeValue
                    appendToNode.AppendChild(newNode)
                End If
            End If
        End If
    Next
    Return returnXmlDoc
     End Function
    

Ciao, Michele

Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. Keep in mind I am using the default settings with Newtonsoft json library and MS XML library, so your mileage may vary:

XML->JSON

  1. All data becomes string data (for example you will always get “false” not false or “0” not 0) Obviously javascript treats these differently in certain cases.
  2. Children elements can become sub object OR sub array depending if there is only one or more than one child element. You would consume these two differently in javascript. The same valid XML can produce actually different JSON structures this way. You can add the attribute json:Array=’true’ to your element to workaround this in some cases.
  3. Your XML must be fairly well-formed, I have noticed it doesnt need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
  4. Blank elements do not convert to JSON. They are ignored. A blank element does not become “element”:null

JSON->XML

  1. You need a top level object that will convert to a root XML element or the parser will fail.
  2. Your object names cannot start with a number, as they cannot be converted to elements (XML is techically even more strict than this, but I can ‘get away’ with breaking all? the other element naming rules.

Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup.

I searched for a long time to find alternative code to the accepted solution in the hopes of not using an external assembly / project. I came up with the following thanks to the source code of the DynamicJson project:

public XmlDocument JsonToXML(string json)
    {
        XmlDocument doc = new XmlDocument();

        using (var reader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), XmlDictionaryReaderQuotas.Max))
        {
            XElement xml = XElement.Load(reader);
            doc.LoadXml(xml.ToString());
        }

        return doc;
    }

Note: I wanted an XmlDocument rather than an XElement for xPath purposes. Also, this code obviously only goes from json to Xml, there are various ways to do the opposite.

Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.

protected object convert(XmlNode root){
    Hashtable obj = new Hashtable();
    for(int i=0,n=root.ChildNodes.Count;i<n;i++){
        object result = null;
        XmlNode current = root.ChildNodes.Item(i);

        if(current.NodeType != XmlNodeType.Text)
            result = convert(current);
        else{
            int resultInt;
            double resultFloat;
            bool resultBoolean;
            if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
            if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
            if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
            return current.Value;
        }

        if(obj[current.Name] == null)
            obj[current.Name] = result;
        else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
            ((ArrayList)obj[current.Name]).Add(result);
        else{
            ArrayList collision = new ArrayList();
            collision.Add(obj[current.Name]);
            collision.Add(result);
            obj[current.Name] = collision;
        }
    }

    return obj;
}

To convert JSON string to XML you can use also the .NET Framework:

using System.Runtime.Serialization.Json;

XDocument xmlDocument = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    new MemoryStream(Encoding.ASCII.GetBytes(jsonString)),
    new XmlDictionaryReaderQuotas()));

Here is the full c# code to convert xml to json

public static class JSon
{
public static string XmlToJSON(string xml)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(xml);

    return XmlToJSON(doc);
}
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<string, object> childNodeNames = new SortedList<string, object>();

    //  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)
    {
        List<object> alChild = (List<object>)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<string, object> 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
    List<object> ValuesAL;

    if (childNodeNames.ContainsKey(nodeName))
    {
        ValuesAL = (List<object>)childNodeNames[nodeName];
    }
    else
    {
        ValuesAL = new List<object>();
        childNodeNames[nodeName] = ValuesAL;
    }
    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();
 }
}

To convert a given XML string to JSON, simply call XmlToJSON() function as below.

string xml = "<menu id=/"file/" value=/"File/"> " +
              "<popup>" +
                "<menuitem value=/"New/" onclick=/"CreateNewDoc()/" />" +
                "<menuitem value=/"Open/" onclick=/"OpenDoc()/" />" +
                "<menuitem value=/"Close/" onclick=/"CloseDoc()/" />" +
              "</popup>" +
            "</menu>";

string json = JSON.XmlToJSON(xml);
// json = { "menu": {"id": "file", "popup": { "menuitem": [ {"onclick": "CreateNewDoc()", "value": "New" }, {"onclick": "OpenDoc()", "value": "Open" }, {"onclick": "CloseDoc()", "value": "Close" } ] }, "value": "File" }}