Question

I've got a legacy web service which I'd like to wrap with a new MVC Web API, question is can I get the ASP.NET Web API to convert my xml into json?

A thought that I had was to use XDocument to create a dynamic object and return that, but when I tried it with an ExpandoObject unfortunately it returned a json object with Key/Value pairs.

Was it helpful?

Solution 3

Turns out this can be done by converting an XDocument to a dynamic JsonObject like so roughly:

var doc = XDocument.Load(uri);
foreach (var node in doc.Root.Descendants()) {
   var obj = (dynamic) new JsonObject();
   foreach (var child in node.Descendants())
   {
      obj[child.Name.LocalName] = child.Value;
      yield return obj;
   } 
}

OTHER TIPS

Using json.NET you can do it easily:

string result = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmldocument);

Download Newtonsoft.Json at http://james.newtonking.com/pages/json-net.aspx

You could. One way to do it would be to deserialize the XML into objects and then serialize them again into JSON.

A more efficient (though harder to code up approach) would be to write your own xml-to-json "transcriber" that reads in the XML and spits out JSON.

Just note that not all XML can be represented easily as JSON.

In WebApiConfig file inside Register function add the below code at last (WebApiConfig file is at App_Start folder)

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top