Sample Code for Parsing JSON string in Java
The sample code below shows you how to parse json string, getting the weater data from a json string that contains weather information from open weather map.
The sample json string containing 7 days of weather data.
{ "city": { "id": 3093133, "name": "Lodz", "coord": { "lon": 19.466669, "lat": 51.75 }, "country": "PL", "population": 0 }, "cod": "200", "message": 0.0099, "cnt": 7, "list": [ { "dt": 1450432800, "temp": { "day": 9, "min": 8.53, "max": 9, "night": 8.58, "eve": 8.53, "morn": 9 }, "pressure": 1019.8, "humidity": 96, "weather": [ { "id": 501, "main": "Rain", "description": "moderate rain", "icon": "10d" } ], "speed": 5.35, "deg": 266, "clouds": 88, "rain": 3.9 }, { "dt": 1450519200, "temp": { "day": 6.93, "min": 6.52, "max": 7.5, "night": 7.23, "eve": 7.31, "morn": 7.24 }, "pressure": 1023.37, "humidity": 98, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "speed": 5.78, "deg": 256, "clouds": 92, "rain": 0.41 }, { "dt": 1450605600, "temp": { "day": 4.76, "min": 4.01, "max": 6.52, "night": 5.33, "eve": 5.82, "morn": 5.25 }, "pressure": 1023.13, "humidity": 98, "weather": [ { "id": 800, "main": "Clear", "description": "sky is clear", "icon": "01d" } ], "speed": 4.62, "deg": 209, "clouds": 0 }, { "dt": 1450692000, "temp": { "day": 5.38, "min": 4.78, "max": 8.5, "night": 7.9, "eve": 7.49, "morn": 4.89 }, "pressure": 1017.68, "humidity": 92, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "speed": 5.48, "deg": 223, "clouds": 88, "rain": 1.67 }, { "dt": 1450778400, "temp": { "day": 10.09, "min": 8.02, "max": 11.65, "night": 11.65, "eve": 10.67, "morn": 8.02 }, "pressure": 1018.9, "humidity": 96, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "speed": 7.56, "deg": 251, "clouds": 92, "rain": 2.52 }, { "dt": 1450864800, "temp": { "day": 13.29, "min": 11.71, "max": 13.29, "night": 11.71, "eve": 12.38, "morn": 12.36 }, "pressure": 1018.69, "humidity": 0, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "speed": 7.19, "deg": 252, "clouds": 89, "rain": 0.26 }, { "dt": 1450951200, "temp": { "day": 10.14, "min": 7.66, "max": 10.6, "night": 7.77, "eve": 7.66, "morn": 10.6 }, "pressure": 1012.27, "humidity": 0, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "speed": 4.83, "deg": 195, "clouds": 44, "rain": 1.43 } ] }
The java code to parse the json string above for get the data you need. It will get 7 days of weather data, the min/max temperatures and weather description for each of those 7 days.
import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class WeatherJsonParser { /** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us. */ public static String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted. final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DESCRIPTION = "main"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); String[] resultStrs = new String[numDays]; for(int i = 0; i < weatherArray.length(); i++) { // For now, using the format "Day, description, hi/low" String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // description is in a child array called "weather", which is 1 element long. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = "day " + i + ", " + description + " - " + highAndLow; } return resultStrs; } /** * Prepare the weather high/lows for presentation. */ private static String formatHighLows(double high, double low) { // For presentation, assume the user doesn't care about tenths of a degree. long roundedHigh = Math.round(high); long roundedLow = Math.round(low); String highLowStr = roundedHigh + "/" + roundedLow; return highLowStr; } }
To use the parser, you just have to call the method getWeatherDataFromJson directly with the weather json string and the number of days. For this sample to work, the number of days has to be at least 7, otherwise you will get array out of boundary error. Ex:
String [] parsedJson = new String[0]; String parsedJsonStr; try { parsedJson = WeatherJsonParser.getWeatherDataFromJson(s, 7); } catch (JSONException e) { System.out.println("JSONException " + e.getMessage()); } for(String weatherStr : parsedJson) { System.out.println("weatherInfo " + weatherStr); }
The output:
day 0, - Rain - 9/9 day 1, - Rain - 8/7 day 2, - Clear - 7/4 day 3, - Rain - 9/5 day 4, - Rain - 12/8 day 5, - Rain - 13/12 day 6, - Rain - 11/8
Reference:
https://gist.github.com/udacityandroid/4ee49df1694da9129af9
Search within Codexpedia
Search the entire web