这是我试图解析/反序列化的Json
{
"transactionId": "c34625a5-0590-48aa-8d1a-978df9aa9010",
"dal": {
"HourlyForecast": {
"geocode:40.77,-73.96:language:en-US:units:e": {
"data": {
"id": "40.77,-73.96",
"vt1hourlyForecast": [{
"processTime": "2017-07-12T12:00:00-0400",
"temperature": 85,
"precipPct": 15,
"precipType": "rain",
"uvIndex": 8,
"icon": 30,
"iconExtended": 3000,
"windDirCompass": "WSW",
"windDirDegrees": 253,
"windSpeed": 6,
"phrase": "Partly Cloudy",
"dayInd": "D",
"severity": 1,
"rh": 62,
"feelsLike": 92
}
//rest of json
我需要访问vt1hourlyForecast[]
我在这里试过了动态的JObject方法
dynamic hourlydata = JObject.Parse(jsonData);
string hourlyForecast = hourlydata["Vt1hourlyForecast"].ToString();
Console.WriteLine(hourlydata);
但我收到错误"无法对空引用执行运行时绑定" 我真的被困在如何正确解析这个。我已经阅读了很多类似的问题,但嵌套的Json真的让我感到困惑,任何帮助都会非常感激。
答案 0 :(得分:0)
您需要导航到list属性vt1hourlyForecast,因为它不是外部对象的属性,而是嵌套属性的属性,例如。
JObject jObject = JObject.Parse(json);
var dal = jObject["dal"];
var hourlyForecast = dal["HourlyForecast"];
var geocode = hourlyForecast["geocode:40.77,-73.96:language:en-US:units:e"];
var data = geocode["data"];
JArray forecast= (JArray)data["vt1hourlyForecast"];
foreach (JProperty forecastProperty in forecast)
{
Console.WriteLine(forecastProperty.Value);
}
在示例代码中,我只是将属性转换为JArray以显示这是可能的,并且它是可枚举的。
答案 1 :(得分:0)
看看这个答案:
您可以执行以下操作:
dynamic myNewObject = JsonConvert.DeserializeObject(json);
会 返回一个可以使用的动态对象。
Console.WriteLine(myNewObject.data[0].description);
显然,它会 如果您的JSON不包含具有对象的数据数组,则会失败 描述属性。
整个问题/答案:https://stackoverflow.com/a/34284972/5056173
基于此,您可以使用NewtonSoft Json获取属性。
另一种方法是自己过滤它:
var startIndex = json.IndexOf("vt1hourlyForecast")-1;
var filteredJson1 = json.Substring(startIndex, json.Length - startIndex);
var endIndex = filteredJson1.IndexOf("}]")+2;
var filteredJson2 = filteredJson1.Substring(0, endIndex);
var jsonValidFilteredJson = "{"+filteredJson2+"}";
var yourObject = JsonConvert.DeserializeObject<Vt1hourlyForecast>(jsonValidFilteredJson);
您可以使用此课程:
public class Vt1hourlyForecast
{
public string processTime { get; set; }
public int temperature { get; set; }
public int precipPct { get; set; }
public string precipType { get; set; }
public int uvIndex { get; set; }
public int icon { get; set; }
public int iconExtended { get; set; }
public string windDirCompass { get; set; }
public int windDirDegrees { get; set; }
public int windSpeed { get; set; }
public string phrase { get; set; }
public string dayInd { get; set; }
public int severity { get; set; }
public int rh { get; set; }
public int feelsLike { get; set; }
}