0

I want to convert a Hashmap of type to a POJO. I am using jackson to convert it currently, however, since the request is a API request, the user might provide more fields than needed. For example, The hashmap could be :

{
  field1ID:"hi",
  field2ID:["HI","HI","JO"],
  field3ID:"bye"
}

while the pojo is simply

{
  field1ID:"hi",
  field3ID:"bye"
}

When using ObjectMapper.convertValue, unless there is a one to one mapping from hashmap to pojo, a IllegalArguemetException will be throw. What I wan to do is, if the field is there then map the field. Else leave it as null.

AzureWorld
  • 311
  • 2
  • 10
  • 3
    have you tried to set the object mapper to not fail on unknown properties? i.e. declare the object mapper as such: `new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)` – scigs Sep 18 '19 at 01:00
  • just annotate pojo with `@JsonIgnoreProperties(ignoreUnknown = true)` – Ryuzaki L Sep 18 '19 at 01:10
  • Take a look at [jackson delay deserializing field](https://stackoverflow.com/questions/17605524/jackson-delay-deserializing-field), [Jackson cannot serialize an my realm object](https://stackoverflow.com/questions/54924580/jackson-cannot-serialize-an-my-realm-object), [Jackson: enum instance methods to return values as strings](https://stackoverflow.com/questions/27049465/jackson-enum-instance-methods-to-return-values-as-strings). – Michał Ziober Sep 18 '19 at 06:41

1 Answers1

0

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>>() {});
cassiomolin
  • 124,154
  • 35
  • 280
  • 359