简体   繁体   中英

Importing some values from hashmap to POJO

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.

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>>() {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM