Web API in WebForms app returning XML instead of JSON

I added Web API to my existing Web Forms (NOT MVC) ASP.NET application using these instructions:



But, they return XML.  
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">

Open in new window

I tried using JSON.NET...
    public string Get(int id)
        DataTable person = MemberFunctions.GetContactInfo(id);
        return JsonConvert.SerializeObject(person);   

Open in new window

and it generates the JSON I need but it is still wrapped in XML tags:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
    [{"Prefix":"Dr","FirstName":"Josh",   ....etc.......   }]

Open in new window

How can I get WebAPI in a WebForms app to return valid JSON instead of XML, preferably using JSON.NET?
Who is Participating?
joshbulaConnect With a Mentor Author Commented:
I ended up just removing the XmlFormatter by putting this in the Global.asax Application_Start (this is an existing WebForms application, originally written in VB, so the Global.asax is VB even though all my new classes and code are C#.)
        Dim formatters = GlobalConfiguration.Configuration.Formatters

Open in new window

But it was still adding quotes and escaping all the quotes, so I realized that it had to return a JObject, not a string, and then Parse it using JObject.Parse:
  public JObject Get(int id)
        DataRow person = MemberFunctions.GetContactInfo(id).Rows[0];
        JObject output = JObject.Parse(JsonConvert.SerializeObject(person));
        return output;

Open in new window

This requires using Newtonsoft.Json.Linq;

To convert an entire datatable or dataset, I ended up just using JsonConvert.SerializeObject without parsing it into a JObject:
string output = JsonConvert.SerializeObject(dataSet, Formatting.None);

Open in new window

and then a Response.Write() and Response.End() to prevent it from adding extra quotes and escaping stuff.

Open in new window

I'm not sure if that's the best way to do that, but it seems to be working.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.