我无法从HTTP请求中检索的JSON对象中检索所有键值。
这是从http请求返回的JSON对象:
{"data":[{"movie_id":3,"movie_name":"Promithius","genre":"a dude","year":"2016","rating":45}]}
我的Android代码:
try {
//HttpJsonParser httpJsonParser = new HttpJsonParser();
JSONObject JSonObj = (JSONObject) new
JSONTokener(result).nextValue();
String mymovie = JSonObj.getString("movie_name" );
String movieGenre = JSonObj.getString("genre" );
etResponse.setText("movie=" + mymovie + " genre=" +
movieGenre);
} catch (JSONException e) {
etResponse.setText("ERROR=" + e.getMessage());
e.printStackTrace();
}
当我仅在模拟器中运行它时:
String mymovie = JSonObj.getString("movie_name" );
etResponse.setText("movie=" + mymovie;
我没有错误地获得了电影名称。所以问题是我可以检索movie_name但没有流派。 返回错误,提示“类型无价值” 预先感谢。
答案 0 :(得分:0)
I think the data is JSONArray.
String result = "{\"data\":[{\"movie_id\":3,\"movie_name\":\"Promithius\",\"genre\":\"a dude\",\"year\":\"2016\",\"rating\":45}]}";
try {
JSONObject JSonObj = (JSONObject) new JSONTokener(result).nextValue();
JSONArray data = JSonObj.getJSONArray("data");
for (int i=0; i<data.length(); i++){
JSONObject jsonObject = data.getJSONObject(i);
String mymovie = jsonObject.getString("movie_name" );
String movieGenre = jsonObject.getString("genre" );
String dest = "movie=" + mymovie + " genre=" + movieGenre;
Log.d(TAG, dest);
}
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
下面是最终对我有用的代码。我希望它可以帮助其他人。
try{
JSONObject object = new JSONObject(result);
JSONArray Jarray = object.getJSONArray("data");
object = Jarray.getJSONObject(0);
String MovieName = object.getString("movie_name");
String Genre = object.getString("genre");
String Rating = object.getString("rating");
String Year = object.getString("year");
etResponse.setText("Movie Name = " + MovieName + " \n Genre = " +
Genre + "\n Rating = " + Rating + " \n Year = " + Year );
} catch (JSONException e) {
etResponse.setText("JSONException: " + e.getMessage());
}