1

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.

  • No specific header => application/xml result
  • Header with content-type assigned to application/json => application/xml result
  • Header with 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 ?

2 Answers 2

3
  • 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, MVC4 RTM. I confirm that it works with an object. My problem is for a simple string. My Json parsers don't recognize "value" as a valid json string.
1

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...
}

1 Comment

The problem is that a string is not automatically serialized. So, your solution is good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.