Convert nested POJO or JSON to Map<String, String>

Viewed 81

In order to create a multipart/form-data request, I need to transform either a nested POJO or the nested JSON that results from Jackson serialization to a Map<String, String> with the following format.

Map<String, String> map = new HashMap<>();
map.put("transaction_id", request.getTransactionId());
map.put("person[dob]", request.getPerson().getDob());
map.put("person[first_name]", request.getPerson().getFirstName());
map.put("person[last_name]", request.getPerson().getLastName());

Here are the definitions of the relevant classes.

@Getter
public class Request {
  @JsonProperty("transaction_id")
  private String transactionId;
  
  private Person person;
}

@Getter
public class Person {
    @JsonProperty("dob")
    private String dob;

    @JsonProperty(value = "first_name")
    private String firstName;

    @JsonProperty(value = "last_name")
    private String lastName;
}

Is there someway to do the map population automatically from a given Request POJO or serialized JSON, e.g. using Jackson that I already use for JSON serialization?

2 Answers

You can convert your Person object into a Map with the ObjectMapper#convertValue that converts an object to a map where the fields' names are keys and values are the fields' values, then add to the obtained map the transaction_id key and its value:

//map will contain keys = {dob, first_name, last_name} 
//up to you modify the keys' names as you like
Map<String, String> map = mapper.convertValue(request.getPerson(),
                             new TypeReference<Map<String, String>>(){});
map.put("transaction_id", request.getTransactionId());

There is no way to do it like you want:

Map<String, String> map = new HashMap<>();
map.put("transaction_id", request.getTransactionId());
map.put("person[dob]", request.getPerson().getDob());
map.put("person[first_name]", request.getPerson().getFirstName());
map.put("person[last_name]", request.getPerson().getLastName());

You could use convertValue method

Map<String, Object> map = mapper.convertValue(request,
                             new TypeReference<Map<String, Object>>(){});

but the resulting map would be something like this:

Map<String, Object> map = new HashMap<>();
map.put("transactionId", request.getTransactionId());
map.put("person", new HashMap<String, Object>());

For reading that map:

String transactionId = map.get("transactionId").toString();
String firstName = ((Map)map.get("person")).get("firstName").toString();
//The same for the rest of the properties
Related