ASP MVC 5 和 Json.NET:动作返回类型

Tom*_*Tom 5 c# asp.net-mvc json.net

我正在使用 ASP MVC 5。我在控制器中有一个返回 json 对象的操作:

[HttpGet]
public JsonResult GetUsers()
{
  return Json(....., JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

现在我想使用 JSON.Net 库,我看到 ASP MVC 5 中还存在。实际上我可以写

using Newtonsoft.Json;
Run Code Online (Sandbox Code Playgroud)

无需从 NuGet 导入库。

现在我试着写:

public JsonResult GetUsers()
{
    return JsonConvert.SerializeObject(....);
}
Run Code Online (Sandbox Code Playgroud)

但是我在编译过程中出现错误:我无法将返回类型字符串转换为 JsonResult。如何在动作中使用 Json.NET?动作的正确返回类型是什么?

Nic*_*aga 5

我更喜欢创建一个object导致自定义的扩展,ActionResult因为它可以在返回时内联应用于任何对象

波纹管扩展使用Newtonsoft Nuget 来序列化对象而忽略空属性

public static class NewtonsoftJsonExtensions
{
    public static ActionResult ToJsonResult(this object obj)
    {
        var content = new ContentResult();
        content.Content = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
        content.ContentType = "application/json";
        return content;
    }
}
Run Code Online (Sandbox Code Playgroud)

下面的示例演示了如何使用扩展。

public ActionResult someRoute()
{
    //Create any type of object and populate
    var myReturnObj = someObj;
    return myReturnObj.ToJsonResult();
}
Run Code Online (Sandbox Code Playgroud)

享受。


Dyg*_*tor 3

ContentResult您可以像这样使用:

return Content(JsonConvert.SerializeObject(...), "application/json");
Run Code Online (Sandbox Code Playgroud)