[英]C# JsonResult with JObject element returns empty array
I am trying to return a JSON result from a REST API that includes a JsonObject as an element. 我正在尝试从包括JsonObject作为元素的REST API返回JSON结果。
var aJsonObject = new JObject();
aJsonObject.Add("somefield", "somevalue" );
aJsonObject.Add("someotherfield", 1995);
return Json( new { status = "success", result = aJsonObject } );
The client receives an empty nested arrays: 客户端收到一个空的嵌套数组:
{"status":"success","result":[[[]],[[]]]}
My work around, which I don't love, is to serialize the JsonObject, thus sending it as a string and then having the client parse it. 我不喜欢的解决方法是序列化JsonObject,从而将其作为字符串发送,然后让客户端对其进行解析。 It works, but it's a bit ugly.
它可以工作,但是有点难看。
Is this a bug or am I doing it wrong? 这是错误还是我做错了?
NOTE: 8/3/18 I edited the variable declaration to correct a typo - it was jsonObject and should have been aJsonObject 注意:18年8月3日,我编辑了变量声明以纠正输入错误-它是jsonObject,应该是aJsonObject
JObject is already json-formatted. JObject已经是json格式的。 Main purpose of JsonResult is to serialize an object to json.
JsonResult的主要目的是将对象序列化为json。 What you are trying to do is (I guess):
您想做的是(我猜):
dynamic resultObject = new ExpandoObject();
resultObject.somefield = "somevalue";
resultObject.someotherfield = 1995;
return Json( new { status = "success", result = resultObject } );
If you want to build the Json string yourself and return it to the client you can use Content: 如果要自己构建Json字符串并将其返回给客户端,则可以使用Content:
return new Content(yourjsonstring, "application/json");
And if you want to keep using JObject, this works (and then return the JSON as @ozum.e describes): 而且,如果您想继续使用JObject,则可以使用它(然后返回@ ozum.e描述的JSON):
var jObject = new JObject();
jObject.Add("someField", "someValue");
jObject.Add("otherField", 1995);
var newObj = new { status = "success", result = jObject };
var returnThis = JsonConvert.SerializeObject(newObj);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.