I'm trying to read a json file and convert to Object and this works fine for other classes but in this case my model has GeoJsonMultiPolygon
which is from package org.springframework.data.mongodb.core.geo;
and does not contain a constructor with no arguments
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `org.springframework.data.mongodb.core.geo.GeoJsonMultiPolygon` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: (BufferedInputStream); line: 12, column: 5] (through reference chain: java.util.ArrayList[0]->data.countryboundaries.CountryBoundaries["geometry"])
Model:
@Getter
@Setter
@ToString()
@EqualsAndHashCode
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
@Document(collection = "country-boundaries")
public class CountryBoundaries {
@Id
private String id;
@EqualsAndHashCode.Exclude
private String type;
@EqualsAndHashCode.Exclude
private CountryBoundariesProperties properties;
@EqualsAndHashCode.Exclude
private GeoJsonMultiPolygon geometry;
}
Code:
ObjectMapper mapper = new ObjectMapper();
InputStream is = Country.class.getResourceAsStream("/country-boundaries.json");
List<CountryBoundaries> countryBoundaries = mapper.readValue(is, new TypeReference<>(){});
countryBoundariesRepository.saveAll(countryBoundaries);
How can I bypass this error since I'm not able to modify code from a library and fill the geometry object using the ObjectMapper?
CodePudding user response:
Check static methods of GeoJsonModule. It contains modules containing serializers and deserializers for geo json classes.
Register with your instance of ObjectMapper
.
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(GeoJsonModule.geoJsonModule());
geoJsonModule()
contains both serializers and deserializers, if you need only deserializers use deserializers()
.