Newtonsoft 作为 jsonResult

Sim*_*mon 6 model-view-controller json

我有 MVC 控制器方法,它应该返回 json 字符串。

public JsonResult myMethod()
{
  ....
  return Json(new { success = true, data = myObject });
}
Run Code Online (Sandbox Code Playgroud)

有用。但 myObject 的列顺序与定义的不同。(Json 根据定义返回无序的名称/值对集)

所以,我使用了 Newtonsoft,并在我的课堂上定义了排序顺序,如下所示:

public class myObject{

 [JsonProperty(Order = 0)]
 public int id { get; set; }

 [JsonProperty(Order = 1)]
 public string name { get; set; }
 }
Run Code Online (Sandbox Code Playgroud)

并且在MVC控制器中必须更改方法以返回字符串而不是JsonResult(我不知道如何使用newtonsoft返回jsonResult)。然后我返回字符串:

return "{ success = true, data = " + Newtonsoft.Json.JsonConvert.SerializeObject(myObject) + "}";
Run Code Online (Sandbox Code Playgroud)

它有效,字符串具有正确的列顺序,但 ajax 方法无法将此字符串识别为 json。那么,最好的解决方案是什么?如何从newtonsoft返回jsonResult而不是json字符串?

小智 0

你可以这样做,我的例子有异步风格,但概念是相同的

public async Task<JsonResult> GetTareasAsync(int proyectoId)
{
   ICollection<Tarea> x = await GetTareasInnerAsync(proyectoId).ConfigureAwait(false);
   return Json(x, new Newtonsoft.Json.JsonSerializerSettings() { MaxDepth = 1  });
}
Run Code Online (Sandbox Code Playgroud)