Stephen Nie Stephen Nie - 1 year ago 46
JSON Question

How would I get a particular value from a JSON?

I'm trying to get a particular value from a field within a JSON file. This is my first time working with a JSON file so I'm not sure if I'm doing it correctly.

try {
URL url = new URL(API_URL + city +".json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {

return stringBuilder.toString();

This block would get the JSON from a weather website and then return the JSON as a string. This string would then be used below. Unfortunately whenever I run this app in Android Studio and go through the logs the logs constantly say that there was no value in

protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";

Log.i("INFO", response);

// TODO: check this.exception
// TODO: do something with the feed

try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String weather = object.getString("weather");
Toast.makeText(MyActivity.this, "There is rain", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {

What I'm trying to do is grab information from the

Here is the JSON link I'm trying to parse from. This text box thought there were too many links in the JSON response for me to post it here. I'm trying to figure out what is going on and any help would be greatly appreciated.

Answer Source

You can print out response to see if it is exactly your JSON or not.

Assume you get the JSON String correctly.

JSONObject object = new JSONObject(response);
String weather = object.getString("weather");

However, if the JSON your obtained is exactly your response, the above code do not work because there is not weather String. The root only contain response and current_observation.

If what you what to get is weather under current_observation, you should use the code below.

JSONObject object = new JSONObject(response);
JSONObject current_obs = object.getJSONObject("current_observation");
String weather = current_obs.getString("weather"); // Clear