2

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.

nieve
  • 4,601
  • 3
  • 20
  • 26

5 Answers5

7

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

udidu
  • 8,269
  • 6
  • 48
  • 68
  • Yeah, that was my initial thought, but I was hoping this could be done by the web api, so that depending on the dataType used (xml or json) the ApiController would return the right format... – nieve Feb 28 '12 at 16:43
  • 1
    Web API does perform content negotiation meaning that it will return a representation that is most appropriate to what the client wants to get. However, it does not have a built in facility for directly converting an XML document into a JSON representation. – marcind Feb 28 '12 at 17:15
2

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.

marcind
  • 52,944
  • 13
  • 125
  • 111
1

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;
   } 
}
nieve
  • 4,601
  • 3
  • 20
  • 26
0

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"));
Sivashankar
  • 493
  • 1
  • 8
  • 17
0
        config.Formatters.Remove(config.Formatters.XmlFormatter);
W34KS
  • 1
  • 1
  • 4
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 28 '20 at 08:19