简体   繁体   English

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

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

I have an ajax call that makes a GET request to one of my controllers action methods.我有一个 ajax 调用,它向我的控制器操作方法之一发出 GET 请求。

The ajax call is supposed to get a JSON response and use that to populate a datagrid. ajax 调用应该得到 JSON 响应并使用它来填充数据网格。 The callback function is supposed to fire and construct the grid and hide the loading indicator.回调 function 应该触发并构建网格并隐藏加载指示器。

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

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

                    });

The problem is when the object I am converting to a JsonResult object has no data - it's just an empty collection.问题是当我正在转换为 JsonResult object 的 object 没有数据时 - 它只是一个空集合。

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

In this example it is the collection myYTDSalesClients that returns empty (which is ok and valid - sometimes there won't be any data).在此示例中,集合myYTDSalesClients返回空值(这是正常且有效的 - 有时不会有任何数据)。

The JSON object then returns an empty response (blank, nadda) and since it's not valid JSON, the callback function won't fire. JSON object 然后返回一个空响应(空白,nadda),因为它无效 JSON,回调 function 不会触发。 Thus the loading indicator still shows and it looks like it's just loading forever.因此加载指示器仍然显示并且看起来它只是永远加载。

So, how do I return an empty JSON result {} instead of a blank?那么,如何返回空的 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());

Use JSON.NET as a default Serializer for serializing JSON instead of default Javascript Serializer:使用 JSON.NET 作为默认的 Serializer 来序列化 JSON 而不是默认的 Javascript Serializer:

This will handle the scenario of sending data if its NULL.这将处理发送数据为 NULL 的情况。

For eg例如

Instead of this in your action method:而不是在您的操作方法中:

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

You need to write this in your action method:你需要在你的动作方法中写下这个:

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

Note: 2nd and 3rd parameter null in above function is to facilitate overloads of Json method in Controller class.注意:上面函数中的第二个和第三个参数为null是为了方便Controller类中Json方法的重载。

Also you do not need to check for null in all of your action methods like above:此外,您无需在上述所有操作方法中检查 null:

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

Below is the code for JsonNetResult class.下面是 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();
    }
}

Also You need to add below code in BaseController if any in your project:如果您的项目中有的话,您还需要在 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
        };
    }

Return Empty JSON {} in ASP.NET Core WebAPI在 ASP.NET 核心 WebAPI 中返回空 JSON {}

Many types of response server status codes do not return content.许多类型的响应服务器状态代码不返回内容。 Even a few of the 200 series Successful Response codes do not allow content to be returned.甚至一些 200 系列成功响应代码也不允许返回内容。 You also must return the 'application/json' content-type in your response for the browser to recognize the JSON, or the browser might interpret empty JSON as null or an empty string.您还必须在响应中返回“application/json”内容类型,以便浏览器识别 JSON,否则浏览器可能会将空的 JSON 解释为 null 或空字符串。 Those two issues might be why you never got your empty JSON object.这两个问题可能就是为什么你从来没有得到你的空 JSON object。

So for this to work, you need to:因此,为此,您需要:

  1. Return the Http Header Status Code of 200 Successful返回Http Header 状态码 200 成功
  2. Return the Http Header Content-type of "application/json"返回Http Header “application/json”的内容类型
  3. Return the empty JSON object {}返回空 JSON object {}

The good news is ASP.NET Core 7 comes with several "ActionResult" subtypes of Response Objects that do all three steps above for you, though the documentation does not clearly state that:好消息是 ASP.NET Core 7 带有几个响应对象的“ActionResult”子类型,它们可以为您完成上述所有三个步骤,尽管文档没有明确 state :

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

// Returns: {}

ObjectResult is a generic wrapper around an ActionResult that includes the ability to return any object converted to JSON, the JSON content-type, and deliver the Status Code 200 Successful. ObjectResult 是 ActionResult 的通用包装器,它能够返回任何转换为 JSON 的 object、JSON 内容类型,并提供状态码 200 Successful。

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

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