Artem
Artem

Reputation: 4639

How to fix Gson JSON parsing from LinkedTreeMap to ArrayList?

I'm using Retrofit+Gson for parsing JSON.

When I try parse response from Google Places API (ok, I don't try parse, I just try to make model for this response) and I get some error.

This is response from Google Place API:

    {
   "predictions" : [
      {
         "description" : "Николаевская область, Украина",
         "id" : "3bd747cc4efc2288da48942b909ce18a053c2060",
         "matched_substrings" : [
            {
               "length" : 5,
               "offset" : 0
            }
         ],
         "place_id" : "ChIJydRVsbqaxUARLq1R8Q3RgpM",
         "reference" : "ClRPAAAAwseWiG8NUMt7TqSqz9rMP8R2M4rX7-cMRmIp4OCYL-VdRSr5B5T_PMwWzYOydVStVpYDvm0ldXYPEzxFAuvn1LqhtWHdROhsERwvmx0tVlwSEFdMw0sOe3rDaB2AqKKmF-YaFLvhiEOz3Bklv5-iTa7QQORILVCU",
         "structured_formatting" : {
            "main_text" : "Николаевская область",
            "main_text_matched_substrings" : [
               {
                  "length" : 5,
                  "offset" : 0
               }
            ],
            "secondary_text" : "Украина"
         },
         "terms" : [
            {
               "offset" : 0,
               "value" : "Николаевская область"
            },
            {
               "offset" : 22,
               "value" : "Украина"
            }
         ],
         "types" : [ "administrative_area_level_1", "political", "geocode" ]
      }, ...],
   "status" : "OK"
}

This is my model for this response:

    public class GetGoogleMapPlacesResponse {
    @SerializedName("predictions")
    private List<GooglePlace> googlePlaces;

    public List<GooglePlace> getGooglePlaces() {
        return googlePlaces;
    }

    public void setGooglePlaces(List<GooglePlace> googlePlaces) {
        this.googlePlaces = googlePlaces;
    }
}

But when Retrofit try's to parse response to model I get error:

java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.myapp.net.rest.response.GetGoogleMapPlacesResponse

And this is raw response in Debug mode: enter image description here

Upvotes: 2

Views: 1683

Answers (1)

mayosk
mayosk

Reputation: 603

You're missing a constructor of GetGoogleMapPlacesResponse model.

public class GetGoogleMapPlacesResponse {
     private List<GooglePlace> googlePlaces;
     private String status;

     public GetGoogleMapPlacesResponse(List<GooglePlace> googlePlaces, String status) {
         this.googlePlaces = googlePlaces;
         this.status = status;
     }

    ...getters & setters
}

But i highly suggest you to use AutoValue with Gson extension and then your model will look like this :

@AutoValue
public abstract class GetGoogleMapPlacesResponse {
      @SerializedName("predictions") public abstract List<GooglePlace> googlePlaces;
      public abstract String status;
}

For more info look here : https://github.com/rharter/auto-value-gson

Upvotes: 1

Related Questions