9

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?

1
  • Why not simply serialize your object using JSON.net, and then write that as a ContentResult? Commented Apr 6, 2011 at 20:40

1 Answer 1

14

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.

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

2 Comments

Thanks, using your input I found the author's following link: james.newtonking.com/archive/2008/10/16/…, which gave me what I was looking for.
But why the code provided in the question does not work?

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.