asp.netwcf-web-apiasp.net-mvc-4asp.net-web-api

Can Web API convert XML into Json?


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.


Solution

  • 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;
       } 
    }