繁体   English   中英

JsonResult - 如何返回一个空的 JSON 结果?

[英]JsonResult - how to return an empty JSON result?

我有一个 ajax 调用,它向我的控制器操作方法之一发出 GET 请求。

ajax 调用应该得到 JSON 响应并使用它来填充数据网格。 回调 function 应该触发并构建网格并隐藏加载指示器。

$.getJSON('@Url.Action("Data", "PortfolioManager")' + '?gridName=revenueMyBacklogGrid&loginName=@Model.currentUser.Login', function (data) {

                        ConstructrevenueMyBacklogGrid(data);
                        $('#revenueMyBacklogLoadingIndicator').hide();

                    });

问题是当我正在转换为 JsonResult object 的 object 没有数据时 - 它只是一个空集合。

returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);

在此示例中,集合myYTDSalesClients返回空值(这是正常且有效的 - 有时不会有任何数据)。

JSON object 然后返回一个空响应(空白,nadda),因为它无效 JSON,回调 function 不会触发。 因此加载指示器仍然显示并且看起来它只是永远加载。

那么,如何返回空的 JSON 结果{}而不是空白?

从 asp.net mvc 5 开始,您可以简单地编写:

Json(new EmptyResult(), JsonRequestBehavior.AllowGet)
if (portfolioManagerPortalData.salesData.myYTDSalesClients == null) {
    returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
}
else {
    returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
}

在 .Net Core 3.0 中,对于 ControllerBase 类型的控制器,您可以执行以下操作:

return new JsonResult(new object());

使用 JSON.NET 作为默认的 Serializer 来序列化 JSON 而不是默认的 Javascript Serializer:

这将处理发送数据为 NULL 的情况。

例如

而不是在您的操作方法中:

return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet)

你需要在你的动作方法中写下这个:

return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, null, null);

注意:上面函数中的第二个和第三个参数为null是为了方便Controller类中Json方法的重载。

此外,您无需在上述所有操作方法中检查 null:

        if (portfolioManagerPortalData.salesData.myYTDSalesClients == null)
        {
            returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
        }
        else
        {
            returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
        }

下面是 JsonNetResult 类的代码。

public class JsonNetResult : JsonResult
{
    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult()
    {
        SerializerSettings = new JsonSerializerSettings();
        JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(ContentType)
          ? ContentType
          : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };

        JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
        serializer.Serialize(writer, Data);

        writer.Flush();
    }
}

如果您的项目中有的话,您还需要在 BaseController 中添加以下代码:

    /// <summary>
    /// Creates a NewtonSoft.Json.JsonNetResult object that serializes the specified object to JavaScript Object Notation(JSON).
    /// </summary>
    /// <param name="data"></param>
    /// <param name="contentType"></param>
    /// <param name="contentEncoding"></param>
    /// <returns>The JSON result object that serializes the specified object to JSON format. The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed.</returns>
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
    {
        return new JsonNetResult
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding
        };
    }

在 ASP.NET 核心 WebAPI 中返回空 JSON {}

许多类型的响应服务器状态代码不返回内容。 甚至一些 200 系列成功响应代码也不允许返回内容。 您还必须在响应中返回“application/json”内容类型,以便浏览器识别 JSON,否则浏览器可能会将空的 JSON 解释为 null 或空字符串。 这两个问题可能就是为什么你从来没有得到你的空 JSON object。

因此,为此,您需要:

  1. 返回Http Header 状态码 200 成功
  2. 返回Http Header “application/json”的内容类型
  3. 返回空 JSON object {}

好消息是 ASP.NET Core 7 带有几个响应对象的“ActionResult”子类型,它们可以为您完成上述所有三个步骤,尽管文档没有明确 state :

[HttpGet]
public IActionResult GetJSON(string? text = "")
{
  return new ObjectResult(new{});
}

// Returns: {}

ObjectResult 是 ActionResult 的通用包装器,它能够返回任何转换为 JSON 的 object、JSON 内容类型,并提供状态码 200 Successful。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM