Skip to content

Instantly share code, notes, and snippets.

@saptak
Created November 29, 2015 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saptak/fbcbf6ef22ae5678c506 to your computer and use it in GitHub Desktop.
Save saptak/fbcbf6ef22ae5678c506 to your computer and use it in GitHub Desktop.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class WeatherDataParser {
/**
* Given a string of the form returned by the api call:
* http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7
* retrieve the maximum temperature for the day indicated by dayIndex
* (Note: 0-indexed, so 0 would refer to the first day).
*/
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
throws JSONException {
// TODO: add parsing code here
final String OWM_LIST = "list";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
JSONObject forecastJson = new JSONObject(weatherJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(dayIndex);
// 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);
return high;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment