开发者

Exception converting JSON.NET JObject to JsonResult

开发者 https://www.devze.com 2023-02-22 08:43 出处:网络
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:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号