我目前正在从网址收集json,但我收到了一个我从未经历过的错误,之后看起来像这样:
Accessed JArray values with invalid key value: "id". Int32 array index expected
这就是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,我需要如何调整代码?
答案 0 :(得分:3)
您正尝试在for循环中引用该数组,请尝试:
System.Diagnostics.Debug.WriteLine(jobs["id"].ToString());
或
System.Diagnostics.Debug.WriteLine(jobs.id.ToString());
您可能还需要解析Json以使其被c#代码解释 见this post about parsing Json with c#