1

I am working on a web API with ASP.NET MVC (.NET 4.5.2) (I'm quite new to ASP) and I would like the change to response format from my controller to be JSON instead of XML.

I tried several things like using the ActionResult return type and returning something like new Json() but this function is not recognized and Visual Studio asks me to create the function.

I'm not sure I'm giving you enough info to help me, so please ask me for more if necessary :)

Thanks!

Jeahel
  • 1,012
  • 2
  • 13
  • 30
  • maybe this helps: http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome – Memet Olsen Feb 27 '15 at 08:26
  • Web API will chose which format to return the data based on the "Accept" header - so if you call your API from a browser it will return XML as that is included in the browser's Accept list, if you call it from an AJAX request it will return json. If you want to see the json in a browser, capture a browser request to your API with fiddler and alter the ACCEPT header to be "application/json" – Carl Feb 27 '15 at 08:27
  • @Jeahel can you provide code how you try? – Grundy Feb 27 '15 at 08:29
  • @Jehael its not an object you need to create... not new Json()... its type is JsonResult and this type is returned by calling the Json() method... https://msdn.microsoft.com/en-us/library/dd504936%28v=vs.118%29.aspx – Florian Schmidinger Feb 27 '15 at 08:44
  • @MemetOlsen this helps; thanks! But then I have two questions: I configured the api to return text/html and in that case i'm not sure how to escape quotes. If I write `return "{\"decision\":\"enable\"}";` in my controller, I get `"{\"decision\":\"enable\"}"` in my browser (so not valid JSON). On the other hand, if I configure with application/json, I still get XML but this time, the string in the XML is fine. Can't I use application/json in the configuration ? – Jeahel Feb 27 '15 at 08:47
  • @FlorianSchmidinger I can't find this method, even if I try using the whole namespace like `System.Web.Mvc.Controller.Json` – Jeahel Feb 27 '15 at 08:51
  • does your controller derive from System.Web.Mvc.Controller ? – Florian Schmidinger Feb 27 '15 at 08:52
  • You don't have to construct the json or xml by yourself! That is the great part of Web API, you just return for example a C# Employee object (so the return type of the method is Employee) and depending on the Accept header, Web API parses the object to either JSON or XML. – Memet Olsen Feb 27 '15 at 08:53
  • the only problem that could occur is if you got a reference cycle in the data. i.e an instance class1 has a reference to an instance of class2 which has has a reference to the first instance class1... – Florian Schmidinger Feb 27 '15 at 08:57
  • @FlorianSchmidinger It derives from `System.Web.Http.ApiController`. Also, I took the project when it already was started so I'm not sure I can change much stuff (plus as I said, I'm not very comfortable with ASP) @MemetOlsen Yes but in fact I'm transmitting data to a Ubudu back end (its a framework for iBeacons management) and I have no model associated with the response I need to send. It simply needs to get a Json string with one variable named `decision` being set to `enable`. – Jeahel Feb 27 '15 at 08:58
  • Edited.... omit the JsonRequestBehavior if you have a post request – Florian Schmidinger Feb 27 '15 at 09:03

2 Answers2

3

All you need to do is this:

 [HttpGet]
 public object Test(string testparameters)
 {
    return new {decision = "enable"};
 }
Florian Schmidinger
  • 4,682
  • 2
  • 16
  • 28
  • Yeah, this is the answer. You can return your models or anonymous types this way. – Alfonso Muñoz Feb 27 '15 at 08:29
  • 2
    `JsonRequestBehavior.AllowGet` not need if request not _GET_ :-) – Grundy Feb 27 '15 at 08:30
  • Ok so with this method I get `{"ContentEncoding":null,"ContentType":null,"Data":{"decision":"enable"},"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}` which is a valid Json string (of course).The problem is that the backend I send my response to waits for pure data, so only the Data variable of my current Json response. any way to do that ? – Jeahel Feb 27 '15 at 09:12
  • Nope I don't :-/ it's juste how the framework works, it needs this response and nothing else – Jeahel Feb 27 '15 at 09:23
  • @FlorianSchmidinger This is the response I get `"{\"decision\":\"enable\"}"`. I think the escape slashes make the Json invalid, right? – Jeahel Feb 27 '15 at 09:55
  • Oh just let me get this straight : i'm not directly testing with the backend, I'm viewing the json in Chrome. Is that a problem? – Jeahel Feb 27 '15 at 10:00
  • i do the same thing... you should test it ... should work fine – Florian Schmidinger Feb 27 '15 at 10:02
  • @Jeahel please forgive me ... updated answer... let me know if it works – Florian Schmidinger Feb 27 '15 at 13:33
  • @Jeahel i should have read the other comment's and immediatly switch where you got that weird jsonresult... what it actually did is serialze the JsonResult with all properties – Florian Schmidinger Feb 27 '15 at 13:35
  • @Jeahel yeah i treated this like a normal controller... but the api controller does the conversion by itsself just like memet olson said.... huge mistake of mine... i just learn mvc myself... preparing for the microsoft exam ... i just did not have this chapter through – Florian Schmidinger Feb 27 '15 at 15:30
2

If you are making use of an ApiController, the client (probably the browser that makes the HTTP request) should specify which type it is expecting.

When the client sends a request message, it can include an Accept header. The Accept header tells the server which media type(s) the client wants from the server. For example:

Accept: text/html,application/xhtml+xml,application/xml

This header tells the server that the client wants either HTML, XHTML, or XML.

The media type determines how Web API serializes and deserializes the HTTP message body. Web API has built-in support for XML, JSON, BSON, and form-urlencoded data, and you can support additional media types by writing a media formatter.

See Media Formatters in ASP.NET Web API 2.

In your case, your request should contain Accept: application/json

Memet Olsen
  • 4,578
  • 5
  • 40
  • 50