gdp
gdp

Reputation: 8232

Jsonresult / request returning json wrapped in XML

I have a method which requests external webservices and returns json here:

    public string GetJsonRequest(string url)
    {
        string response = string.Empty;
        var request = System.Net.WebRequest.Create(url) as HttpWebRequest;
        if (request != null)
        {
            request.Method = WebRequestMethods.Http.Get;
            request.Timeout = 20000;
            request.ContentType = "application/json";


            var httpresponse = (HttpWebResponse)request.GetResponse();

            using (var streamreader = new StreamReader(httpresponse.GetResponseStream()))
                   response = streamreader.ReadToEnd();

            if (httpresponse != null) httpresponse.Close();
        }
        return response;
    }

And a method which returns the result here:

    public JsonResult Makes()       
    {
        CarRepository rep = new CarRepository();
        return new JsonResult()
        {
            Data = rep.GetMakes(),
            ContentType = "application/json"
        };
    }

or

    public string Makes()       
    {
        CarRepository rep = new CarRepository();
        return rep.GetMakes();
    }

This returns correct json but it is wrapped in XML

<JsonResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <ContentType>application/json</ContentType>
   <Data xsi:type="xsd:string">
       The JSON data.......
   </Data>
  <JsonRequestBehavior>AllowGet</JsonRequestBehavior>
  <MaxJsonLength xsi:nil="true"/>
  <RecursionLimit xsi:nil="true"/>
</JsonResult>

I have checked the request in fiddler and the Accept headers only have xml values in. How can i get this to just print out json? I am using the ASP.NET Web API. I can remove the XML mediatypeformatter on application start, but i might need to use it later on down the line so i dont think thats the way to go.

Thanks in advance

Upvotes: 0

Views: 3039

Answers (2)

JayC
JayC

Reputation: 39

Instead of returning a string in your WebMethod use:

JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(YOUR_STRING_TO_OUTPUT));

Upvotes: 0

tpeczek
tpeczek

Reputation: 24125

You shouldn't be returning JsonResult from ApiController action. ApiController actions should return objects (or collections) and the MediaTypeFormatters are taking care of serializng them to the JSON, XML or anything else (based on content type requested). Please take a look at this basic tutorial.

UPDATE

To make sure that client is requesting for JSON (not XML) and the Web API will try to use proper MediaTypeFormatter add this to your client:

request.Accept = "application/json";

Upvotes: 2

Related Questions