将JSON.NET JObject转换为JsonResult的异常 [英] Exception converting JSON.NET JObject to JsonResult
问题描述
我有一个JSON.NET JObject,其数据结构如下:
I have a JSON.NET JObject with data structured like this:
{
"foo" : {
"bar": "baz"
}
}
我正尝试将其转换为ASP.NET MVC JsonResult,如下所示:
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原为 用户代码未处理.无法访问 重视孩子 Newtonsoft.Json.Linq.JValue.
InvalidOperationException was unhandled by user code. Cannot access child value on Newtonsoft.Json.Linq.JValue.
我有一个解决方法,可以迭代JObject的所有属性,然后将它们解析为一个通用对象,如下所示:
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, ... });
但是,这似乎容易出错,并且像解决该问题的不必要的非通用方式一样.有什么方法可以更有效地执行此操作,希望使用JSON.NET或ASP.NET MVC中的一些内置方法吗?
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);
}
其中:
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));
}
}
拥有一个JObject似乎是过大的选择,您可以使用.NET JavaScriptSerializer将该序列化为JSON,该JavaScript更常与某些模型类结合使用.
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.
这篇关于将JSON.NET JObject转换为JsonResult的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!