lukso lukso - 2 years ago 203
JSON Question

Converting JSON to XML

I trying to convert JSON output into XML. Unfortunately I get this error:

JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.

This is what I up to now created.

string url = string.Format("{0}?fields=posts.fields(message)&access_token={1}", user_name, access_token);

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
StreamReader reader = new StreamReader(response.GetResponseStream());
jsonOutput = reader.ReadToEnd();
Console.WriteLine("THIS IS JSON OUTPUT: " + jsonOutput);
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonOutput);

And this is my JSON output:


How can I solve this problem?

Answer Source

Despite the fact your JSON provided in the question is not complete, you have multiple properties at the top level as indicated by the exception. You have to define the root for it to get valid XML:

var doc = JsonConvert.DeserializeXmlNode(jsonOutput, "root");

EDIT: In order to print out your XML with indentation you can use XDocument class from System.Xml.Linq namespace: XDocument.Parse(doc.InnerXml).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download