JSON Weather Parser
Once
we have created our model we have to parse it. We can create a specific
class that handles this task. First we have to create the “root” object
that receive as input the entire string containing all the JSON
response:
2 | JSONObject jObj = new JSONObject(data); |
Then we start parsing each piece of the response:
02 | Location loc = new Location(); |
04 | JSONObject coordObj = getObject( "coord" , jObj); |
05 | loc.setLatitude(getFloat( "lat" , coordObj)); |
06 | loc.setLongitude(getFloat( "lon" , coordObj)); |
08 | JSONObject sysObj = getObject( "sys" , jObj); |
09 | loc.setCountry(getString( "country" , sysObj)); |
10 | loc.setSunrise(getInt( "sunrise" , sysObj)); |
11 | loc.setSunset(getInt( "sunset" , sysObj)); |
12 | loc.setCity(getString( "name" , jObj)); |
13 | weather.location = loc; |
In the line 4,8 we create two “sub” object (coordObj and sysObj)
having as parent the jObj as it clear from the JSON response. As we can
see we use some helper methods to get String,int and float values:
01 | private static JSONObject getObject(String tagName, JSONObject jObj) throws JSONException { |
02 | JSONObject subObj = jObj.getJSONObject(tagName); |
06 | private static String getString(String tagName, JSONObject jObj) throws JSONException { |
07 | return jObj.getString(tagName); |
10 | private static float getFloat(String tagName, JSONObject jObj) throws JSONException { |
11 | return ( float ) jObj.getDouble(tagName); |
14 | private static int getInt(String tagName, JSONObject jObj) throws JSONException { |
15 | return jObj.getInt(tagName); |
And
then we finally parse the weather information. We have to remember that
weather tag is an array so we have to handle it differently
02 | JSONArray jArr = jObj.getJSONArray( "weather" ); |
05 | JSONObject JSONWeather = jArr.getJSONObject( 0 ); |
06 | weather.currentCondition.setWeatherId(getInt( "id" , JSONWeather)); |
07 | weather.currentCondition.setDescr(getString( "description" , JSONWeather)); |
08 | weather.currentCondition.setCondition(getString( "main" , JSONWeather)); |
09 | weather.currentCondition.setIcon(getString( "icon" , JSONWeather)); |
11 | JSONObject mainObj = getObject( "main" , jObj); |
12 | weather.currentCondition.setHumidity(getInt( "humidity" , mainObj)); |
13 | weather.currentCondition.setPressure(getInt( "pressure" , mainObj)); |
14 | weather.temperature.setMaxTemp(getFloat( "temp_max" , mainObj)); |
15 | weather.temperature.setMinTemp(getFloat( "temp_min" , mainObj)); |
16 | weather.temperature.setTemp(getFloat( "temp" , mainObj)); |
19 | JSONObject wObj = getObject( "wind" , jObj); |
20 | weather.wind.setSpeed(getFloat( "speed" , wObj)); |
21 | weather.wind.setDeg(getFloat( "deg" , wObj)); |
24 | JSONObject cObj = getObject( "clouds" , jObj); |
25 | weather.clouds.setPerc(getInt( "all" , cObj)); |
At the end we have our Weather class filled with the data retrieved.
No comments:
Post a Comment