Reputation: 1455
I am currently gathering json from a url but i recieve an error that i have never experienced before looking like this:
Accessed JArray values with invalid key value: "id". Int32 array index expected
This is how the JSON looks (an example of 1 item, there are more of these):
[
{
"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
}
]
How i gather the 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;
}
}
How i try to use it and where the error occurs:
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
}
How would I need to adjust my code in order to successfully gather the JSON?
Upvotes: 4
Views: 10424
Reputation: 177
You are trying to reference the array within the for loop, try:
System.Diagnostics.Debug.WriteLine(jobs["id"].ToString());
or
System.Diagnostics.Debug.WriteLine(jobs.id.ToString());
You might also need to parse your Json for it to be interpreted by c# code see this post about parsing Json with c#
Upvotes: 4