3

I need to override/fix the serialization mechanism for a 3rd party class (google maps classes) so that I can marshal the objects in from a file on disk. I have seen several examples of what I am trying to do and none of them seems to work.

The troubled class:

public class LatLng implements UrlValue {
    public double lat;
    public double lng;

    public LatLng(double lat, double lng) {
        this.lat = lat;
        this.lng = lng;
    }
}

My mixin

public abstract class LatLnMixIn {
    @JsonCreator
    public LatLnMixIn(@JsonProperty("lat") Double lat, @JsonProperty("lng ")Double lng) {}
}

My usage

 ObjectMapper mapper = new ObjectMapper().addMixIn(LatLng.class, LatLnMixIn.class);
    InputStream mockStream = this.getClass().getResourceAsStream("/mz-to-nordstrom-rack-snoq.json");
    DirectionsResult mockResult = mapper.readValue(mockStream, DirectionsResult.class);

snippet of the json to be marshaled:

      "start_location" : {
        "lat" : 47.5985728,
        "lng" : -122.3315845
      },

My error (with/without mixin)

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.google.maps.model.LatLng]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

Does anyone see where I might have gone wrong?

Community
  • 1
  • 1
Christian Bongiorno
  • 5,150
  • 3
  • 38
  • 76

1 Answers1

3

Mixins work with matching constructor and method signatures. Your target class constructor looks like

public LatLng(double lat, double lng)

while your mixin constructor is defined as

public LatLnMixIn(Double lat, Double lng)

Jackson considers double and Double as different types and therefore doesn't find a matching constructor in the target class.

Simply change your constructor to use double parameters.


The @JsonCreator annotation is unnecessary in this specific example.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724