Jay
Jay

Reputation: 910

Dynamic with Json.NET

I'm trying to deserialize some Json into a Dynamic using Json.NET. Following the examples given at Deserialize json object into dynamic object using Json.net. I've got most of the way there, however I'm having difficulty with one part of the Json where it includes [] around the contents. I've placed the returned Json at the top of the top below.

//{ "coord":{ "lon":-0.13,"lat":51.51},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],
//  "base":"cmc stations","main":{"temp":283.582,"pressure":1024.62,"humidity":91,"temp_min":283.582,"temp_max":283.582,
//  "sea_level":1034.82,"grnd_level":1024.62},"wind":{"speed":6.61,"deg":222},"clouds":{"all":92},"dt":1449047315,
//"sys":{"message":0.0052,"country":"GB","sunrise":1449042313,"sunset":1449071662},"id":2643743,"name":"London","cod":200}

var url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0";

// Synchronous Consumption
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);

dynamic d = JObject.Parse(content);

//Can now do d.weather

dynamic d2 = d.weather;
//var weatherMain = d.weather.main; // this doesn't work :( -- I think because because the sub-json has more [] around it

dynamic d3 = d.coord;
var lon = d3.lon; //this works

var pink = 2;

I would like to retrieve the value of d.weather.main, but I think the [] brackets are preventing it. I've tried replacing them, but it seems to break the dynamic structure if I do this.

Upvotes: 0

Views: 74

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156928

You should provide the index of the weather instance you want to get since your weather property in your JSON is an array (indicated by the [] surrounding it):

d.weather[0].main;

Upvotes: 3

Related Questions