Why is JSON document not fully consumed?

后端 未结 2 1922
挽巷
挽巷 2021-01-20 08:15

I\'m trying to retrieve JSON data from an external source for practice. I have gotten all the code in place but for some reason I get an error saying that the document is no

相关标签:
2条回答
  • 2021-01-20 09:05

    Your completeJSONdata is incorrect as you are always putting "null" towards the end.

    Instead your while clause should be for example :

            while ((myJSON = bufferedReaderObject.readLine()) != null) {
                completeJSONdata += myJSON;
            }
    

    By the way, don't forget to close your streams for instance by using a try with :

    try (InputStream inputStreamObject = httpURLConnection.getInputStream()) {
    // ...
    }
    
    0 讨论(0)
  • The value is being pass, but however null is also getting passed with it so use an if statement rather than using while like this..

    if (myJSON != null) {
                    myJSON = bufferedReaderObject.readLine();
                    completeJSONdata += myJSON;
                }
    

    then convert in Gson like this..

        Gson gson = new Gson();
        deserializedContainerObject = gson.fromJson(completeJSONdata, DeserializedContainer.class);
    

    write the getters and setters in DeserializedVariables class

    public String getMovieName() {
             return movieName;
         }
    
         public void setMovieName(String movieName) {
             this.movieName = movieName;
         }
    
         public Integer getMovieYear() {
             return movieYear;
         }
    
         public void setMovieYear(Integer movieYear) {
             this.movieYear = movieYear;
         }
    
         public Double getMovieRating() {
             return movieRating;
         }
    
         public void setMovieRating(Double movieRating) {
             this.movieRating = movieRating;
         }
    

    And now you can retrieve it in your onPostExecute() like this..

    @Override
        protected void onPostExecute( DeserializedContainer result) {
    
            mListener.onSuccess( result );
    
            for (int i = 0; i <result.deserializedContainerList.size(); i++) {
                DeserializedVariables deserializedVariables = result.deserializedContainerList.get(i);
                Log.d( TAG, "onPostExecuss: " + deserializedVariables.getMovieName() );
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题