ThomQ
ThomQ

Reputation: 605

How can List<Customclass> be filled with LinkedHashMaps, rather then instances of Customclass?

I'm having trouble understanding why in the example below, the customclass lists(response.results and results) are filled with LinkedHashMaps. I'd expected after parsing the JSON inputstream, the lists just to be full of customclasses, with their classmembers containing the data, straight from JSON. Instead, the Lists come back containing LinkedHashMaps, even though they are type Customclass.

Could anyone explain?

Gson gson = new Gson();
Reader reader = new InputStreamReader(inputStream);

PlacesList response = gson.fromJson(reader, PlacesList.class);

List<Place> results = response.results;

Customclasses used:

public class PlacesList implements Serializable {

    @Key
    public String status;

    @Key
    public String error_message;

    @Key
    public List<Place> results;

}

&

public class Place implements Serializable {

    @Key
    public String id;

    @Key
    public String name;

    @Key
    public String reference;

    @Key
    public String icon;

    @Key
    public String vicinity;

    @Key
    public Geometry geometry;

    @Key
    public String formatted_address;

    @Key
    public String formatted_phone_number;

    @Override
    public String toString() {
        return name + " - " + id + " - " + reference;
    }


    public static class Geometry implements Serializable
    {
        @Key
        public Location location;
    }

    public static class Location implements Serializable
    {
        @Key
        public double lat;

        @Key
        public double lng;
    }

}

Upvotes: 1

Views: 52

Answers (1)

thkala
thkala

Reputation: 86443

The JSON format does not contain any type information, except for its own primitive types. It is a text-based format, with arrays and objects mapped respectively to whatever concept of ordered list and ordered key-value pair list exists in each programming language.

Therefore a LinkedHashMap is a natural representation of a JSON object in Java. As such, it is what most JSON deserializers output by default.

To retrieve custom objects in all JSON implementations that I have used you need to either supply a custom deserializer class, or to post-process the output of the standard deserializer. Occasionally it may even be necessary for a custom serializer to assist by inserting some type information in the JSON stream to resolve ambiguous cases.

Upvotes: 1

Related Questions