2

I am using asp.net mvc 4. Looking at some tutorials I have created my own JsonResult class inheriting from OOB JsonResult class to use Json.Net. Below is how my class looks.

public class JsonNetResult : JsonResult
{
    private readonly object _data;

    public JsonNetResult(object data)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        _data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        var writer = new JsonTextWriter(response.Output);
        var serializer = JsonSerializer.Create(new JsonSerializerSettings());
        serializer.Serialize(writer, _data);
        writer.Flush();
    }
}

What I wanted to ask is

  1. whether this class is required, or .net is using Json.Net internally for serializing the object.
  2. Also can I directly bind a serialized model to the view.
3
  • The answer to 1 is no. You can use the built in JavaScriptSerializer class to achieve it. Commented Apr 4, 2013 at 16:12
  • The answer to 2 is you could, using a string, but why would you want to do that? Commented Apr 4, 2013 at 16:13
  • @mattytommo:I know I can use built in JavaScriptSerializer. From what I have read, JSON.Net is far better than built in options. Commented Apr 4, 2013 at 16:19

1 Answer 1

3

For Web API, the MS team used the Newtonsoft library; Scott Hanselman declaring it as vastly superior at a conference I went to.

Unfortunately, they didn't bake it into MVC4 (wish they had), so you have to put in your own implementation of it along the lines of what you're doing:

http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx

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

Comments

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.