【问题标题】:Cannot read JSON returned by .Net Core controller on client side无法在客户端读取 .Net Core 控制器返回的 JSON
【发布时间】:2021-04-28 20:16:24
【问题描述】:

在我的控制器中,我有一个由AJAX 调用触发的方法。我有一个要返回的字符串列表

List<string> Usernames = new List<string>();

然后当数据加载到Usernames时,我将其转换为JSON

var JsonResults = Json(Usernames);

最后我返回JSON,如下所示

return Json(new { success = true, resultsList =JsonResults });

在 JavaScript 中,如何循环遍历该数组 resultsList?这是 JS 代码的样子 -

$.ajax({
    url: "@Url.Action("StartNewChat")",
    data: { SearchedText: searchedText },
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if (result.success == true) {

            // READ THROUGH result.resultsList                
        }
    }
});

我尝试了JSON.parse()result.resultsList[0] 并将result.resultsList 转换为字符串并返回到JSON,但没有成功。

编辑:
当我执行console.log(result.resultsList) 时,我得到的结果很奇怪

{"contentType":null,"serializerSettings":null,"statusCode":null,"value":["a","aa","aaa"]}

最后一个数组是c#Username数组的结果

【问题讨论】:

  • 您使用的是哪个版本的 .NET Core?
  • 它的 .Net Core 5

标签: javascript json asp.net-core


【解决方案1】:

我不熟悉您使用的 Json 方法,但是从 3.1 版开始,.Net Core 有自己的 json 序列化程序 JsonSerializer(在 System.Text.Json 命名空间中),我将在我的回答。

就您的问题而言,您正在序列化两次,它可能不会在您的最终结果中将resultsList 作为您可能期望的字符串数组提供给您。

您的第一次转换将产生一个字符串数组 -

["alice","bob","charlie"]

但是根据所使用的序列化程序,您的第二次转换可能会将上面的整个数组放在一个字符串中,并在最终结果中将其作为 resultsList 的值。

你应该序列化一次,只序列化最终的对象 -

// you need to import the following
// using System.Text.Json;

List<string> userNames = new List<string>();
names.Add("alice");
names.Add("bob");
names.Add("charlie");

return JsonSerializer.Serialize(new { success = true, resultsList = userNames });

它会给你resultsList作为一个字符串数组-

{"success":true,"resultsList":["alice","bob","charlie"]}

然后你可以在客户端循环遍历该数组,例如 -

result.resultsList.forEach(p=> console.log(p))

【讨论】:

    【解决方案2】:

    响应已经有一个JSON,所以不需要解析任何东西。

    会是这样的:

    $.ajax({
    
                  url: "@Url.Action("StartNewChat")",
                  data: { SearchedText: searchedText},
                  type: "GET",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function (result) {
                    if (result.success == true)
                    {
                          
                        result.resultsList.forEach( el => {
                            console.log(el)
                        })
                          
                    }
                }
            });
        });
        ```
    

    【讨论】:

    • 没有工作 JS 错误:result.resultsList.forEach is not a function
    • 我认为原因是 C# 中的 JSON() 实际上也返回了一些其他的东西?!
    【解决方案3】:

    有时你必须先解析 json 响应,试试这个。紧接着成功线

    let result = JSON.parse(result);

    然后

    if (result.success == true)
    {                      
      result.resultsList.forEach( el => {
        console.log(el)
      })                      
    }
    

    【讨论】:

      【解决方案4】:

      你可以通过结果列表长度来试试这个。

                $.ajax({
                url: "@Url.Action("StartNewChat")",
                data: { SearchedText: searchedText},
                type: "GET",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                  if (result.success == true)
                  {
                   for (var i = 0; i <result.resultsList.length; i++) {
                         console.log(result.resultsList[i]);
                     }     
                  }
              }
          });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多