8

I have a JSON.NET JObject with data structured like this:

{
    "foo" : {
        "bar": "baz"
    }
}

I'm trying to convert it to a ASP.NET MVC JsonResult as follows:

JObject someData = ...;
JsonResult jsonResult = Json(someData, "application/json", JsonRequestBehavior.AllowGet);

When I do this, I get the following exception:

InvalidOperationException was unhandled by user code. Cannot access child value on Newtonsoft.Json.Linq.JValue.

I have a workaround, in that I can iterate through all of the properties of the JObject, and parse them into a generic object like so:

JsonResult jsonResult = Json(new { key1 = value1, key2 = value2, ... });

However, this seems error prone and like an unnecessary non-generic way of solving this problem. Is there any way I can do this more efficiently, hopefully using some built in methods in JSON.NET or ASP.NET MVC?

Raul Agrait
  • 5,850
  • 6
  • 47
  • 71
  • Why not simply serialize your object using JSON.net, and then write that as a ContentResult? – Tejs Apr 06 '11 at 20:40

1 Answers1

15

If you have a JObject I would recommend you writing a custom ActionResult which directly serializes this JObject using JSON.NET into the response stream. It is more in the spirit of the MVC pattern:

public ActionResult Foo()
{
    JObject someData = ...;
    return new JSONNetResult(someData);
}

where:

public class JSONNetResult: ActionResult
{
    private readonly JObject _data;
    public JSONNetResult(JObject data)
    {
        _data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/json";
        response.Write(_data.ToString(Newtonsoft.Json.Formatting.None));
    }
}

It seems like an overkill to have a JObject which you would serialize into JSON using the .NET JavaScriptSerializer which is more commonly used in conjunction with some model classes.

Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
  • 2
    Thanks, using your input I found the author's following link: http://james.newtonking.com/archive/2008/10/16/asp-net-mvc-and-json-net.aspx, which gave me what I was looking for. – Raul Agrait Apr 06 '11 at 21:13