Stephen Nie Stephen Nie - 4 months ago 10
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) {
stringBuilder.append(line).append("\n");
}

bufferedReader.close();
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
weather
.

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

progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(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) {
e.printStackTrace();
}
}


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

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

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
Comments