在Android中使用JSON解析图像网址和日期

时间:2017-03-06 22:02:32

标签: java android json

我试图解析java中的JSON对象:

{
        "poster_path": "/e3QX3tY0fBR1GuxdP0mwpN16cqI.jpg",
        "adult": false,
        "overview": "In 1950s Pittsburgh, a frustrated African-American father struggles with the constraints of poverty, racism, and his own inner demons as he tries to raise a family.",
        "release_date": "2016-12-16",
        "genre_ids": [
            18
        ],
        "id": 393457,
        "original_title": "Fences",
        "original_language": "en",
        "title": "Fences",
        "backdrop_path": "/jNlCIAcheh0iOuL3kz9x1Wq9WLG.jpg",
        "popularity": 10.976374,
        "vote_count": 290,
        "video": false,
        "vote_average": 6.7
    },

但是当我尝试访问poster_path的值(org.json.JSONException:没有poster_path的值)和release_date(org.json.JSONException:release_date没有值)时,我得到一个JSONException

   ArrayList<MovieModel> results = new ArrayList<MovieModel>();
            String streamAsString = result;
            try{
                JSONObject jsonObject = new JSONObject(streamAsString);
                JSONArray array = (JSONArray) jsonObject.get("results");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject c = array.getJSONObject(i);
                    JSONObject jsonMovie = array.getJSONObject(i);
                    MovieModel movieModel= new MovieModel();
                    movieModel.setMovieTitle(jsonMovie.getString("title"));
                    movieModel.setMovieGenre("na");;
                  String strImgURL=jsonObject.getString("poster_path").substring(2);
                    movieModel.setImgURL("");
                    movieModel.setMovieYear(jsonObject.getString("release_date"));
                    results.add((movieModel));
                }
            }
            catch(JSONException j)
            {
                System.err.println(j);
                Log.d(DEBUG_TAG, "Error parsing JSON. String was: " + j.toString());
            }

不确定导致此错误的原因

1 个答案:

答案 0 :(得分:3)

您正在尝试从外部JSONObject获取poster_pathrelease_date值,这些值包含所有内容(包括包含各个电影的JSONArray)。

在循环中,只需使用jsonMovie代替jsonObject

for (int i = 0; i < array.length(); i++) {
    JSONObject jsonMovie = array.getJSONObject(i);
    MovieModel movieModel= new MovieModel();
    movieModel.setMovieTitle(jsonMovie.getString("title"));
    movieModel.setMovieGenre("na");
    String strImgURL=jsonMovie.getString("poster_path").substring(2);
    movieModel.setImgURL("");
    movieModel.setMovieYear(jsonMovie.getString("release_date"));
    results.add((movieModel));
}