Reputation:
I am trying to read a JSON object and get the value of a certain key. Here is a screenshot of what the JSON object looks like:
Here is the code I'm using:
private void sendRequest(){
try{
URL url = new URL(ROOT + searchString + "&token=" + MYAPIKEY);
HttpURLConnection http = (HttpURLConnection)url.openConnection();
InputStream inputStream = http.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
JSONObject testobject = new JSONObject(bufferedReader.readLine());
String plot = testobject.getString("plot");
//String plot = testobject.getString("plot:");
publishProgress(plot);
bufferedReader.close();
inputStream.close();
http.disconnect();
}
catch (IOException e){
Log.e("ERROR", e.getMessage(), e);
publishProgress(); //No data were found
} catch (JSONException e) {
e.printStackTrace();
}
}
When I run the above code I get the following error:
W/System.err: org.json.JSONException: No value for plot
It is as if there is a JSON Object, but the object doesn't contain a key named "plot". (I tried with "plot:" as well, but that didn't work either.)
Question: How do I get the value from the plot-key?
Upvotes: 0
Views: 855
Reputation: 2985
First you need to parse the data
object and then movies
Array from data. After Iterating th
JSONObject testobject = new JSONObject(bufferedReader.readLine());
JSONObject dataJson = testobject.getJSONObject("data")
JSONArray moviesArray = dataJson.getJSONArray("movies");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject jsonObj = moviesArray.getJSONObject(i);
if(jsonObj.has("plot")){
String plot = jsonObj.getString("plot");
}
}
Upvotes: 0
Reputation: 8237
Try this .
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray movies = data.getJSONArray("movies");
for (int i = 0; i < movies.length(); i++) {
JSONObject jo = movies.getJSONObject(i);
// add has method
if(jo.has("plot")){
String plot = jo.getString("plot");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 4