Din*_*uka -1 .net c# json json.net
我需要将此JSON字符串解析为我的"WeatherJson"类型的对象.但是我不知道如何解析字符串中的阵列,如"'天气’: [{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}].实体类会是什么样子?
JSON字符串:
{
"coord": {"lon":79.85,"lat":6.93},
"sys": {
"type": 1,
"id": 7864,
"message": 0.0145,
"country": "LK",
"sunrise": 1435883361,
"sunset": 1435928421
},
"weather": [
{"id":802, "main":"Clouds", "description":"scattered clouds", "icon":"03d"}
],
"base": "stations",
"main": {
"temp": 302.15,
"pressure": 1013,
"humidity": 79,
"temp_min": 302.15,
"temp_max": 302.15
},
"visibility":10000,
"wind": { "speed": 4.1, "deg": 220 },
"clouds": { "all": 40 },
"dt": 1435893000,
"id":1248991,
"name":"Colombo",
"cod":200
}
Run Code Online (Sandbox Code Playgroud)
编辑
我需要从代码中检索以下值:
WeatherJson w = new WeatherJson();
Console.WriteLine(w.weather.description);
//that above line was retrieved and stored from the JSONArray named 'weather' in the main json response
Run Code Online (Sandbox Code Playgroud)
您应该只使JSON中的数组与POCO中的列表或数组类型匹配.这是使用您提供的JSON的简短但完整的示例:
using System;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
class Test
{
static void Main(string[] args)
{
var json = File.ReadAllText("weather.json");
var root = JsonConvert.DeserializeObject<Root>(json);
Console.WriteLine(root.Weather[0].Description);
}
}
public class Root
{
// Just a few of the properties
public Coord Coord { get; set; }
public List<Weather> Weather { get; set; }
public int Visibility { get; set; }
public string Name { get; set; }
}
public class Weather
{
public int Id { get; set; }
public string Description { get; set; }
}
public class Coord
{
public double Lon { get; set; }
public double Lat { get; set; }
}
Run Code Online (Sandbox Code Playgroud)