如何在 C# 中检查 json 数组是否为空?
How to check if json array is empty in c#?
我正在调用 Google 地图并使用 System.JSON 来解析对象。我使用以下方法抓取我的对象:
double placeLat = json["results"][0]["geometry"]["location"]["lat"];
然后我想检查是否存在第三个对象,如果是,则执行一些操作,但显然以下操作失败。我知道在这种情况下 Google 映射 returns 2 个对象,我想检查第三个对象以避免对 null 执行操作并进一步传递它们。当 Google 时以下工作正常映射 returns 3 个对象,所以我认为我的情况是错误的。
if (json["results"][2] != null) {
}
我收到此错误:
Index was out of range. Must be non-negative and less than the size of
the collection. Parameter name: index
关于如何在使用 System.JSON 的情况下正确构建 if 语句的任何想法?
如果结果数组中只有两个条目,则无法访问 json["results"][2]
,因为索引 2 超出了数组的范围。
在访问索引 2 之前,请检查 json["results"].Count
以确保索引 2 存在。在访问计数之前,您可能需要将其转换为 JsonArray
。
if(jsonobject.Count>0)
{
}
var response = await httpClient.PostAsync(uri, content);
var instituteDetails = await response.Content.ReadAsStringAsync();
**if (response.IsSuccessStatusCode && instituteDetails.Length>2)**
{
createModel = JsonConvert.DeserializeObject<IList<PaymentResponseDetailsModel>>(instituteDetails);
**if(createModel.Count()>0)**
{
return View(createModel);
}
else
{
return RedirectToAction("RegistrationInfo");
}
});
}
我正在调用 Google 地图并使用 System.JSON 来解析对象。我使用以下方法抓取我的对象:
double placeLat = json["results"][0]["geometry"]["location"]["lat"];
然后我想检查是否存在第三个对象,如果是,则执行一些操作,但显然以下操作失败。我知道在这种情况下 Google 映射 returns 2 个对象,我想检查第三个对象以避免对 null 执行操作并进一步传递它们。当 Google 时以下工作正常映射 returns 3 个对象,所以我认为我的情况是错误的。
if (json["results"][2] != null) {
}
我收到此错误:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index
关于如何在使用 System.JSON 的情况下正确构建 if 语句的任何想法?
如果结果数组中只有两个条目,则无法访问 json["results"][2]
,因为索引 2 超出了数组的范围。
在访问索引 2 之前,请检查 json["results"].Count
以确保索引 2 存在。在访问计数之前,您可能需要将其转换为 JsonArray
。
if(jsonobject.Count>0)
{
}
var response = await httpClient.PostAsync(uri, content);
var instituteDetails = await response.Content.ReadAsStringAsync();
**if (response.IsSuccessStatusCode && instituteDetails.Length>2)**
{
createModel = JsonConvert.DeserializeObject<IList<PaymentResponseDetailsModel>>(instituteDetails);
**if(createModel.Count()>0)**
{
return View(createModel);
}
else
{
return RedirectToAction("RegistrationInfo");
}
});
}