C#:提取/检索JSON结构的子节点 [英] C# : extract/retrieve child node from JSON structure
问题描述
我们怎样才能提取或检索子节点从C#JSON结构值
How can we extract or retrieve child nodes values from JSON structure in C#.
我的应用程序正在使用的 OpenWeatherMap ,我需要检索的名称从 城市的 温度从 列表的和说明从 天气的节点,我的JSON和阶级结构都低于
my app is using OpenWeatherMap, I need to retrieve name from city, temp from list and description from weather nodes, my JSON and Class structure are below
{
"cod": "200",
"message": 0.0284,
"city": {
"id": 2643743,
"name": "London",
"coord": {
"lon": -0.12574,
"lat": 51.50853
},
"country": "GB",
"population": 0,
"sys": {
"population": 0
}
},
"cnt": 1,
"list": [
{
"dt": 1429268400,
"temp": {
"day": 12.21,
"min": 4.86,
"max": 13.18,
"night": 4.86,
"eve": 11.76,
"morn": 12.21
},
"pressure": 1028.8,
"humidity": 66,
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"speed": 5.9,
"deg": 67,
"clouds": 80
}
]
}
C#类
public class WeatherForeCast
{
public string City { get; set; }
public decimal Day { get; set; }
public decimal Min { get; set; }
public decimal Max { get; set; }
public decimal Night { get; set; }
public string Description { get; set; }
}
截至日期我熟悉使用JSON.net进行序列化和反序列化C#对象JSON具有相同的结构。
Till date I'm familiar with using JSON.net for serialize and deserialize C# objects to JSON which has exact same structure.
推荐答案
如果你只是想填充的一个实例WeatherForecast
,你可以使用一些 SelectToken
调用一个普通的 JObject
:
If you just want to populate an instance of WeatherForecast
, you could use a few SelectToken
calls on a plain JObject
:
var parsed = JObject.Parse(json);
var forecast = new WeatherForeCast();
forecast.City = parsed.SelectToken("city.name").Value<string>();
forecast.Day = parsed.SelectToken("list[0].temp.day").Value<decimal>();
forecast.Description = parsed.SelectToken("list[0].weather[0].description").Value<string>();
forecast.Min = parsed.SelectToken("list[0].temp.min").Value<decimal>();
forecast.Max = parsed.SelectToken("list[0].temp.max").Value<decimal>();
forecast.Night = parsed.SelectToken("list[0].temp.night").Value<decimal>();
请注意,这是相当脆弱,虽然,它使有关JSON的内容假设。如果JSON的变化, SelectToken
的路径,各种属性将是不正确的,这个代码将抛出异常。
Note that this is pretty brittle though, it's making assumptions about the contents of the JSON. If the JSON changes, the path to various properties in SelectToken
will be incorrect and this code will throw an exception.
这篇关于C#:提取/检索JSON结构的子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!