Search code examples
javaandroidjsongsonpojo

Member field gets ignored when parsing using gson


I am parsing a POJO into json using Google's gson library. These are the objects involved:

// Order.java
public class Order {
    // ...
    private int id;
    private String name;
    private Location location;
    // ...
}
// Location.java
public class Location {
    // ...
    private String address;
    private float latitude;
    private float longitude;
    private String postcode
    // ...
}

When I run it though gson (making sure the Location member variable is not null) using new Gson().toJson(order) I get this results:

{
    "id" : 1,
    "name" : "nameValue"
}

but I was expecting to get something like this:

{
    "id" : 1,
    "name" : "nameValue",
    "location" : {
            "address" : "some address",
            "latitude" : 53.346346,
            "longitude" : -3.346363,
            "postcode" : "23563"
        }
}

Can't figure out why is this happening. Has anybody come across this? What can it be that I may be doing wrong?

I have tried setting a custom Type adapter with no luck.

Thanks for your help.


Solution

  • Ok, I figured out what the issue was. I had a mock object factory that created the mock objects using anonymous constructor in the Location type, like this:

    Location location = new Location() {
        {
             setAddress("some address");
             setLatitude(53.346346);
             setLongitude(-3.356363);
             setPostCode("23563");
        }
    };
    

    So Gson interpreted it as an anonymous class and as it is said in the documentation:

    Fields corresponding to the outer classes in inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization

    I changed it into the normal way of setting up the GsonBuilder and iworks as expected. However I wonder if it would be possible to use this kind of initiation, since it does work for Collections (ArrayList). It makes my mock factories easier to read. :)