我正在尝试读取JSON对象并获取某个键的值。 以下是JSON对象的截图:
以下是我使用的代码:
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();
}
}
当我运行上面的代码时,我收到以下错误:
W / System.err:org.json.JSONException:没有情节值
就好像有一个JSON对象,但该对象不包含一个名为" plot"的键。 (我试过"剧情:"同样,但那也没有奏效。)
问题:如何从plot-key中获取值?
答案 0 :(得分:2)
试试这个。
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();
}
答案 1 :(得分:0)
首先,您需要解析data
对象,然后从数据中解析movies
数组。迭代后
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");
}
}