0

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:

The JSON Object

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?

2
  • Plot is inside 2 arrays (if its inside gender, its 3), one called data and one called movies. You need to search within those two arrays. A foreach inside a foreach and inside the 2nd, the String plot = testobject.getString("plot"); should do the trick Commented Oct 13, 2017 at 16:13
  • 1
    Possible duplicate of How to parse JSON in Android Commented Oct 13, 2017 at 16:31

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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");
    }
}

1 Comment

It's under data.movies[i].genres.plot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.