How can I deserialize a JSON to a Java class which has known mandatory fields, but can have several unknown fields?
You can use JsonAnySetter
annotation:
class PersonDTO { @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; private Map<String, String> extras = new HashMap<>(); @JsonAnySetter public void setExtras(String name, String value) { this.extras.put(name, value); } // No args constructor // Getters // Setters}
See also:
There are couple of things that you can do if you are using Jackson:-
- You can make use of @JsonAnyGetter and @JsonAnySetter annotation and create your class as:-
import com.fasterxml.jackson.annotation.JsonAnyGetter;import com.fasterxml.jackson.annotation.JsonAnySetter;import java.util.HashMap;import java.util.Map;public class PersonDTO { // mandatory field private String firstName; // mandatory field private String lastName; // Unknown optional fields? // Capture all other fields that Jackson do not match other members @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } // No args constructor // Getters // Setters}
- If you don't want the unknown fields in your PersonDTO then you can simply ignore unknown properties using annotation @JsonIgnoreProperties at class level eg
@JsonIgnoreProperties(ignoreUnknown = true)public class PersonDTO { //TODO:- }
- The ObjectMapper can also be configured to ignore unknowns e.g.:-
new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)