Reputation: 5356
I looked at the JSON.NET site but I am not getting it... I already have code like this ..
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
that turns objects into json... So I looked at JSON.NET and that seems to do the same thing ? What am I missing ? What isa simple example of what JSON.NET can do that I can do with
protected internal JsonResult Json(object data);
??
Upvotes: 1
Views: 585
Reputation: 8242
For the Web API in MVC 4 the default serializer is the json.net library, however when returning a JsonResult in MVC 4 from standard controllers the default serializer used is JavascriptSerializer. You can create a custom jsonresult and override the Json method in standard controllers to use the Json.Net library by default.
To use json.net you can first create a custom result:
public class JsonNetResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("Controller Context");
}
HttpResponseBase response = context.HttpContext.Response;
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
var jsonData = JsonConvert.SerializeObject(Data);
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
response.Write(jsonData);
}
}
Then override the json method in a base controller method and return json like your currently doing:
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult() {
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding
};
}
Upvotes: 1