Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : extract/retrieve child node from JSON structure

Tags:

json

c#

json.net

How can we extract or retrieve child nodes values from JSON structure in C#.

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# Class

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; }
}

Till date I'm familiar with using JSON.net for serialize and deserialize C# objects to JSON which has exact same structure.

like image 395
BeingDev Avatar asked Apr 17 '15 14:04

BeingDev


2 Answers

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>();

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.

like image 67
Andrew Whitaker Avatar answered Sep 16 '22 17:09

Andrew Whitaker


Use json2csharp.com to generate your classes.

public class Coord
{
    public double lon { get; set; }
    public double lat { get; set; }
}

public class Sys
{
    public int population { get; set; }
}

public class City
{
    public int id { get; set; }
    public string name { get; set; }
    public Coord coord { get; set; }
    public string country { get; set; }
    public int population { get; set; }
    public Sys sys { get; set; }
}

public class Temp
{
    public double day { get; set; }
    public double min { get; set; }
    public double max { get; set; }
    public double night { get; set; }
    public double eve { get; set; }
    public double morn { get; set; }
}

public class Weather
{
    public int id { get; set; }
    public string main { get; set; }
    public string description { get; set; }
    public string icon { get; set; }
}

public class List
{
    public int dt { get; set; }
    public Temp temp { get; set; }
    public double pressure { get; set; }
    public int humidity { get; set; }
    public List<Weather> weather { get; set; }
    public double speed { get; set; }
    public int deg { get; set; }
    public int clouds { get; set; }
}

public class RootObject
{
    public string cod { get; set; }
    public double message { get; set; }
    public City city { get; set; }
    public int cnt { get; set; }
    public List<List> list { get; set; }
}

Then use JSON.NET to deserialize into the class structure and extract the properties you want.

var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);

You now have an instance of RootObject and you can traverse it as needed to extract the specific value(s) you need.

like image 34
Craig W. Avatar answered Sep 17 '22 17:09

Craig W.