Saranya
Saranya

Reputation: 201

How to parse specific data of this JSON in .Net?

This is my Json:

{
 "coord": {
  "lon": -0.13,
  "lat": 51.51
 },
 "weather": [{
  "id": 520,
  "main": "Rain",
  "description": "light intensity shower rain",
  "icon": "09d"
 }],
 "base": "stations",
 "main": {
  "temp": 289.42,
  "pressure": 1008,
  "humidity": 55,
  "temp_min": 287.15,
  "temp_max": 291.15
 },
 "visibility": 10000,
 "wind": {
  "speed": 4.1,
  "deg": 340
 },
 "rain": {
  "1h": 4.32
 },
 "clouds": {
  "all": 40
 },
 "dt": 1463937214,
 "sys": {
  "type": 1,
  "id": 5091,
  "message": 0.0474,
  "country": "GB",
  "sunrise": 1463889474,
  "sunset": 1463947050
 },
 "id": 2643743,
 "name": "London",
 "cod": 200
}

I want to deserialize this into a weather report class. I am interested only in this part of the data.

"main":{"temp":289.42,"pressure":1008,"humidity":55,"temp_min":287.15,"temp_max":291.15}

So I would like to create a class something like the below

class weather
{ 
var temp,pressure,humidity,..
}

Could someone please advise how I can use the DeserializeObject here?

Upvotes: 0

Views: 44

Answers (2)

Radin Gospodinov
Radin Gospodinov

Reputation: 2323

Use json.net. http://www.newtonsoft.com/

Here is how to deserialize only the part that you need. Basically the class needs to contains the only the properties that you want to use and they must match the json vars.

var definition = new { temp = "" };

var weatherReport = JsonConvert.DeserializeAnonymousType(yourString, definition);

Upvotes: 1

shayD_16
shayD_16

Reputation: 1

If you are the one providing the service which returns the quoted JSON response I would strongly recommend that you edit the response to provide you with only the required data. This would not only reduce the data/time per request but would make processing it on the client much more efficient. However, if that is not an option I believe you can use this link to get some idea about getting specific values of the JSON response as required.

However, the other option is to simply deserialize the entire object and get the required data since the performance difference between getting a specific part vs the entire object is not significant unless the JSON is significantly large.

Upvotes: 0

Related Questions