Returning an anonymous type from MVC 4 Web Api fails with a serialization error

You could also use the JsonMediaTypeFormatter so you do not need the JSONObject and related classes. Then you can return a dynamic type in your controller class.

public static void Register(HttpConfiguration config)
{
    config.Formatters.Clear();            
    config.Formatters.Add(new JsonMediaTypeFormatter());
    config.MapHttpAttributeRoutes();
}

public class YourController : ApiController
{        
    [HttpGet, Route("getstuff/{stuffId}")]
    public dynamic Get(string stuffId)
    {
        var stuff = Model.Stuff.Get(stuffId);

        return new {
            success= stuff != null,
            stuffId = stuff.Id,
            name = stuff.Name
        };
    }
}

If you also want to support Jsonp you can inherit the JsonMediaTypeFormatter and create you own JsonpMediaTypeFormatter (which also can be found on stackoverflow: https://stackoverflow.com/a/12492552/1138266).


If you look at the Fiddler (sample in here I use Firefox)

enter image description here

By default, request from browser will accepts application/xml, not application/json

But, you can create fake request from Fiddler by adding one header:

Accept: application/json

It will work

From the link:

The XML serializer does not support anonymous types or JObject instances. If you use these features for your JSON data, you should remove the XML formatter from the pipeline, as described later in this article.

How to remove XmlFormatter:

  var configuration = GlobalConfiguration.Configuration;
  configuration.Formatters.Remove(configuration.Formatters.XmlFormatter);