Home > Enterprise >  @JsonIgnoreProperties(ignoreUnknown = true) does not have expected behaviour
@JsonIgnoreProperties(ignoreUnknown = true) does not have expected behaviour

Time:04-13

I'm working on a feature on which I get an address from outside, and need to parse it into a Java class:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AddressDTO {
    @JsonProperty(value = "Name")
    private String name;
    @JsonProperty("Street")
    private String street;
    @JsonProperty("City")
    private String city;
    @JsonProperty("PostalCode")
    private String postalCode;
    @JsonProperty("CountryISO")
    private String countryIso;
    @JsonProperty("Region")
    private String region;
}

and this os how I convert it:

        try {
            final var type = new TypeReference<AddressDTO>() {
            };
            final var address = (AddressDTO) new ObjectMapper()
                    .readerFor(type)
                    .readValue(jsonAddress);

            return mapper.toAddress(address);
        } catch (final Exception e) {
            LOG.error("unable to parse the variable 'address'", e);
            throw new BadFormatException();
        }

I want only those fields, but it may happend that sometimes the payload from outside also contains "Street2", "Name2" or other fields. When this happens, this exception is thrown: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Street2".

After having search how to solve this, I came accross the property @JsonIgnoreProperties(ignoreUnknown = true), which is supposed to ignore unknown fields:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true) // Some old value might contain additional old fields            
  • Related