Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception converting JSON.NET JObject to JsonResult

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?

like image 753
Raul Agrait Avatar asked Apr 06 '11 20:04

Raul Agrait


1 Answers

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.

like image 99
Darin Dimitrov Avatar answered Nov 05 '22 23:11

Darin Dimitrov