JSON.NET JObject to JsonResult conversion exception

I have a JObject JSON.NET with data structured as follows:

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

I am trying to convert it to 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. Unable to access value for child Newtonsoft.Json.Linq.JValue.

I have a workaround in which I can iterate over all the properties of a JObject and parse them into a common object, for example:

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

However, this seems error prone and as an unnecessary non-general way to solve this problem. Is there a way to do this more efficiently, hopefully using some of the built-in methods in JSON.NET or ASP.NET MVC?

+7
source share
1 answer

If you have a JObject, I would recommend you write a custom ActionResult that directly serializes this JObject using JSON.NET into the response stream, This is more like an 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 that the redundant code has a JObject that you would serialize to JSON using the .NET JavaScriptSerializer, which is more often used in conjunction with some model classes.

+13
source

All Articles