I'm trying to return a JObject as my action resuls. I've used Newtonsoft.Json
and JsonNetResult for converting objects to JsonResult. For normal objects, I use this syntax for serializing objects into JsonResult:
当我的行动产生时,我试图返回一份工作。我用Newtonsoft。Json和JsonNetResult用于将对象转换为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 i.e. [[[]]]
:
myResult是想要的对象的实例,但是要为JObject (Newtonsoft.Json.Linq.JObject)尝试此操作,如下所示,返回无效结果,即[[[[[]]]:
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 ?
1 个解决方案
#1
0
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!
希望这可以帮助!
#1
0
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!
希望这可以帮助!