1
votes

I have a JSON structure like below.

json={
    "page": {
        "mode": "2",
        "ref": "user"
    }
}

I am using the following code for converting JSON to XML.

Reference: http://www.flowgearcoder.net/2013/04/03/convert-between-json-and-xml

  var dynamicObject = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(Json);
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(dynamicObject.GetType());

        MemoryStream ms = new MemoryStream();
        serializer.Serialize(ms, dynamicObject);

        Xml = System.Text.Encoding.UTF8.GetString(ms.ToArray());

I am getting the following error while executing the xmlSerializer conversion.

The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], [System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

Can anyone help me figure out this issue?

3
Why do you want to convert it to XML? Just asking because in a previous question someone wanted to convert to XML first, then deserialize the xml into objects. If this is your plan you are better off deserializing the json itselfhavardhu
stackoverflow.com/questions/679050/… See this earlier QA for infohavardhu
@havardhu, I want to convert JSON to HTML. SO in first step i will convert JSON to XML and then to HTML. Can you identify the issue?Tom Cruise
@Precious1tj, why you mentioned the URL that i added for reference in my question itself?Tom Cruise
Can you post your json string?jekcom

3 Answers

1
votes

It can easily be converted to xml using Json.Net

string xml = JsonConvert.DeserializeXNode(json).ToString();
0
votes

JavaScriptSerializer.DeserializeObject cast json string to Dictionary<String, Object>.

Dictionary is not supported by XMLSerializer. So if you're creating json yourself, you might want to change its structure and use JavaScriptSerializer.Deserialize<T> method to cast it to specific class and latter serialize it to XML.

0
votes

As an alternative to the JavaScriptSerializer, you may use Json.NET:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Xml;

public class Test
{
    public static void Main()
    {
        var json = @"{""page"":  {""mode"": ""2"", ""ref"": ""user""}}";
        var xmlDocument = new XmlDocument();
        var d=  xmlDocument.CreateXmlDeclaration("1.0","utf-8","yes");
        xmlDocument.AppendChild(d);
        var xml = JsonConvert.DeserializeXmlNode(json);
        var root = xmlDocument.ImportNode(xml.DocumentElement,true);
        xmlDocument.AppendChild(root);
        Console.WriteLine(xmlDocument.OuterXml);
    }
}

Outputs:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<page><mode>2</mode><ref>user</ref></page>