gpt4 book ai didi

c# - "Accessed JArray values with invalid key value: "id ". Int32 array index expected"收集json时崩溃

转载 作者:行者123 更新时间:2023-11-30 20:28:31 46 4
gpt4 key购买 nike

我目前正在从一个 url 收集 json,但我收到了一个我从未遇到过的错误,看起来像这样:

使用无效键值访问 JArray 值:“id”。应为 Int32 数组索引

这是 JSON 的样子(1 个项目的示例,还有更多):

[  
   {  
      "id":19205,
      "company_id":2658,
      "external_link":"",
      "county":{  
         "id":12,
         "name":" ",
         "future":"",
         "infrastructure":""
      },
      "category":{  
         "id":5,
         "name":""
      },
      "company":{  
         "id":2658,
         "company_info":[  

         ]
      },
      "merits":[  

      ],
      "reqs":[  
         {  
            "id":56548,
            "ad_id":19205
         },
         {  
            "id":56549,
            "ad_id":19205
         },
         {  
            "id":56550,
            "ad_id":19205
         },
         {  
            "id":56551,
            "ad_id":19205
         },
         {  
            "id":56552,
            "ad_id":19205
         }
      ],
      "contact":null
   }
]

我如何收集 json:

static public async Task<JArray> getData()
{
var httpClientRequest = new HttpClient();
try
{
var result = await httpClientRequest.GetAsync("https://mydata.com");
var resultString = await result.Content.ReadAsStringAsync();
var jsonResult = JArray.Parse(resultString);
return jsonResult;
}

catch
{
return null;
}
}

我如何尝试使用它以及发生错误的地方:

var getData = await dataApi.getData();

foreach (var jobs in getData)
{
System.Diagnostics.Debug.WriteLine(getData["id"].ToString()); //CRASH: `Accessed JArray values with invalid key value: "id". Int32 array index expected
}

我需要如何调整我的代码才能成功收集 JSON?

最佳答案

你正试图在 for 循环中引用数组,尝试:

System.Diagnostics.Debug.WriteLine(jobs["id"].ToString());

System.Diagnostics.Debug.WriteLine(jobs.id.ToString());

您可能还需要解析您的 Json 以使其由 C# 代码解释见this post about parsing Json with c#

关于c# - "Accessed JArray values with invalid key value: "id ". Int32 array index expected"收集json时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47268521/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com