Friday, 15 September 2017

Working on Json datas: if a key is missing

One of the things I have lernt today it was the possibility to know if an element on an Json array exists. The necessity of this is information is strong to prevent a NullPointException.

For exemple (on an Openweathermap string) we have this information in Json format:

{"coord":{"lon":18.17,"lat":40.36},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":296.18,"pressure":1013,"humidity":100,"temp_min":295.15,"temp_max":297.15},"visibility":10000,"wind":{"speed":1.5},"clouds":{"all":0},"dt":1505505300,"sys":{"type":1,"id":5746,"message":0.0031,"country":"IT","sunrise":1505449736,"sunset":1505494485},"id":6542124,"name":"Lecce","cod":200}

As you can see there at least one difference (I marked in red):
{"coord":{"lon":18.17,"lat":40.36},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":296.14,"pressure":1013,"humidity":83,"temp_min":295.15,"temp_max":297.15},"visibility":10000,"wind":{"speed":5.1,"deg":190},"clouds":{"all":0},"dt":1505506500,"sys":{"type":1,"id":5749,"message":0.0022,"country":"IT","sunrise":1505449738,"sunset":1505494482},"id":6542124,"name":"Lecce","cod":200} 
Yes, in these second infos the data value for "deg" is missing.


How we can resolve it?

Well, we can use the has method, so we can write something like this:

if (json.getJSONObject("wind").has("deg"))

Well done...

No comments:

Post a Comment