Reputation: 1468
I just create a new WebApi project and keep the default controller :
public class ValuesController : ApiController
{
// GET api/values/5
public string Get(int id)
{
return "value";
}
//other services...
}
When I try to request it, I can't get a valid JSON result.
application/xml
result content-type
assigned to application/json
=> application/xml
result accept
assigned to application/json
gives me a correct response content-type
but a malformed JSON : "value"
.What is the way to get a valid JSON result ?
Upvotes: 1
Views: 4605
Reputation: 10185
- No specific header => application/xml result
- Header with content-type assigned to application/json => application/xml result
Are you using MVC 4 RTM? The default format should be application/json if you are using MVC 4 RTM... I am unable to repro your scenario.
- Header with accept assigned to application/json gives me a correct response content-type but a malformed JSON : "value".
"value" is actually a valid JSON value for string. If you are looking for the format of a name/value pair, here is an example. Say I have a class called 'Person' ...
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
... and I have a action that returns a person object,
public Person Get()
{
return new Person() { Id = 1, FirstName = "John", LastName = "Doe" };
}
then the call to the above action will return this:
{"Id":1,"FirstName":"John","LastName":"Doe"}
Hope this helps.
Upvotes: 3
Reputation: 9651
You will have to use JsonResult
as your return type:
public class ValuesController : ApiController
{
// GET api/values/5
public JsonResult Get(int id)
{
object returnObject;
// do here what you need to get the good object inside returnObject
return this.Json(returnObject, JsonRequestBehavior.AllowGet);
}
// other services...
}
Upvotes: 1