As you didn't provide any code in your question, consider, for example, you have a map as shown below:
Map<String, Object> map = new HashMap<>();
map.put("firstName", "John");
map.put("lastName", "Doe");
map.put("emails", Arrays.asList("johndoe@mail.com", "john.doe@mail.com"));
map.put("birthday", LocalDate.of(1990, 1, 1));
And you want to map it to and instance of Contact
:
@Data
public class Contact {
private String firstName;
private String lastName;
private List<String> emails;
}
It could be achieved with the following code:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
Contact contact = mapper.convertValue(map, Contact.class);
In the example above, the map has a birthday
key, which cannot be mapped to any field of the Contact
class. To prevent the serialization from failing, the FAIL_ON_UNKNOWN_PROPERTIES
feature has been disabled.
Alternatively, you could annotate the Contact
class with @JsonIgnoreProperties
and set ignoreUnknown
to true
:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Contact {
...
}
And then perform the conversion:
ObjectMapper mapper = new ObjectMapper();
Contact contact = mapper.convertValue(map, Contact.class);
To convert the Contact
instance back to a map, you can use:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.convertValue(contact,
new TypeReference<Map<String, Object>>() {});