[英]ASP.NET MVC: return JObject as JsonResult
I'm trying to return a JObject as my action resuls.我正在尝试返回一个 JObject 作为我的操作结果。 I've used
Newtonsoft.Json
and JsonNetResult for converting objects to JsonResult.我使用
Newtonsoft.Json
和JsonNetResult将对象转换为 JsonResult。 For normal objects, I use this syntax for serializing objects into JsonResult:对于普通对象,我使用以下语法将对象序列化为 JsonResult:
return new JsonResult
{
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8,
Data = myResult,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
Which myResult
is instance of a desired object, However trying this for a JObject ( Newtonsoft.Json.Linq.JObject
) as below, returns invalid result ie [[[]]]
:其中
myResult
是所需 object 的实例,但是尝试对 JObject ( Newtonsoft.Json.Linq.JObject
. [[[]]]
ie
JObject jsonObject = new JObject();
jsonObject["error"] = "invalid_id";
return new JsonResult
{
ContentType = "application/json",
ContentEncoding = System.Text.Encoding.UTF8,
Data = jsonObject,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
How can I serialize JObject in this case?在这种情况下如何序列化 JObject?
You can try: 你可以试试:
public JsonObject GetJson_1()
{
var errors = new Dictionary<string, string>();
errors.Add("Id", "invalid");
return new JsonObject(errors);
}
public ActionResult GetJson_2()
{
var errors = new List<object>();
errors.Add(new { Id = "invalid" });
return Json(errors, JsonRequestBehavior.AllowGet);
}
Hope this helps! 希望这可以帮助!
This worked for me !!这对我有用!
var serialized = JsonConvert.SerializeObject(response,
new JsonSerializerSettings() {
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
return new ContentResult()
{
Content = serialized,
ContentType = "application/json",
};
response is an instance of a c# class that contains a property of type JObject.响应是包含 JObject 类型属性的 c# class 的实例。 This caused Ok(response) to return empty array symbols ([]) for every property inside the jobject.
这导致 Ok(response) 为 jobject 中的每个属性返回空数组符号([]) 。 Manually serializing and returning it as a contentresult solved it for me.
手动序列化并将其作为内容结果返回为我解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.