在解析json之后,即使null值不为null,也会返回null值

时间:2016-07-15 19:45:42

标签: android

{
  "page": 1,
  "results": [
    {
      "poster_path": "/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
      "adult": false,
      "overview": "Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
      "release_date": "2014-10-10",
      "genre_ids": [
        18,
        10402
      ],
      "id": 244786,
      "original_title": "Whiplash",
      "original_language": "en",
      "title": "Whiplash",
      "backdrop_path": "/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
      "popularity": 7.361171,
      "vote_count": 1949,
      "video": false,
      "vote_average": 8.32
    }
  ]
}

这是我的JSON响应,但是当我解析它时,id的值始终为null 下面是我的网络和JSON解析代码,请帮助..

public class movietask extends AsyncTask<String, Void, List<movieobject>> {
    private String TAG;
    private static final String Base_string = "http://api.themoviedb.org/3/movie/";
    private static final String api_key = "388e5684ea2f3bb8de279874cb6990a5";
    private static final String MOVIE_ID="id";
    private static final String MOVIE_OVERVIEW="overview";
    private static final String MOVIE_TITLE="original_title";
    private static final String MOVIE_VOTE="vote_average";
    private static final String MOVIE_POSTERPATH="poster_path";
    private static final String MOVIE_RELEASE_DATE="release_date";
    private static final String MOVIE_BACKDROP_PATH="backdrop_path";

    // Parse json data to get arraylist of movieobjects

    private List<movieobject> getparseddata(String forecastjsonstr)
            throws JSONException {
        final String START_OF_JSON = "results";
        JSONObject startlist = new JSONObject(forecastjsonstr);
        JSONArray startarray = startlist.getJSONArray(START_OF_JSON);
        int noofobjects = startarray.length();
        List<movieobject> objectarray = new ArrayList<>();
        for (int i = 0; i < noofobjects; i++) {
            JSONObject object = startarray.getJSONObject(i);
            movieobject finalobjectarray = new movieobject();
            finalobjectarray.setMovieId(object.getString(MOVIE_ID));
            finalobjectarray.setOverview(object.getString(MOVIE_OVERVIEW));
            finalobjectarray.setTitle(object.getString(MOVIE_TITLE));
            finalobjectarray.setMovieRating(object.getString(MOVIE_VOTE));
            finalobjectarray.setPosterPath(object.getString(MOVIE_POSTERPATH));
            finalobjectarray.setReleaseDate(object.getString(MOVIE_RELEASE_DATE));
            finalobjectarray.setBackdroppath(object.getString(MOVIE_BACKDROP_PATH)+"/10");
            objectarray.add(finalobjectarray);
        }

        return objectarray;

    }



    protected List<movieobject> doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        List<movieobject> finalobjectarray = new ArrayList<>();

        // Will contain the raw JSON response as a string.
        String forecastJsonStr = null;

        try {


            URL url = new URL(Base_string + params[0] + "?api_key="+api_key);


            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // Read the input stream into a String
            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.

            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return null;

            }
            forecastJsonStr = buffer.toString();
            Log.i("hey", "Hello" + forecastJsonStr);
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }
        }

        try {
            finalobjectarray = getparseddata(forecastJsonStr);
        } catch (JSONException e) {
            Log.e("Json exception", e.getMessage(), e);
            e.printStackTrace();
        }

        return finalobjectarray; //final movieobject array
    }


    //onPostExecute method of asynctask

    protected void onPostExecute(List<movieobject> results) {
    }
}

2 个答案:

答案 0 :(得分:2)

ID为null因为&#34; id&#34;不是字符串。

让我们检查你的JSON。

{  
   "page":1,
   "results":[  
      {  
         "poster_path":"/lIv1QinFqz4dlp5U4lQ6HaiskOZ.jpg",
         "adult":false,
         "overview":"Under the direction of a ruthless instructor, a talented young drummer begins to pursue perfection at any cost, even his humanity.",
         "release_date":"2014-10-10",
         "genre_ids":[  
            18,
            10402
         ],
         "id":244786,                            <------- Without "" = Integer
         "original_title":"Whiplash",            <-------- With "" = String
         "original_language":"en",
         "title":"Whiplash",
         "backdrop_path":"/6bbZ6XyvgfjhQwbplnUh1LSj1ky.jpg",
         "popularity":7.361171,
         "vote_count":1949,
         "video":false,
         "vote_average":8.32
      }
   ]
}

因此,要获得该值,您将使用 getInt()

finalobjectarray.setMovieId(object.getInt(MOVIE_ID).toString());

答案 1 :(得分:1)

这可能会有所帮助。理想情况下,电影对象中的MovieId应为int:

finalobjectarray.setMovieId(""+object.getInt(MOVIE_ID));