Skip to content

Converting POJO into map

I have a Java class having 10 attributes, I want to convert this into 3 maps(Breaking it into 5,3,2 fields resepectively). I did some research and found that Jackson’s ObjectMapper can be used by doing something like this:

/**
 * Using Jackson Databind.
 */
import java.util.HashMap;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonExample {
    
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    @SuppressWarnings("unchecked")
    public HashMap<String, Object> convert(Person person) {
        
        HashMap<String, Object> hashMap = objectMapper.convertValue(person, HashMap.class);
        return hashMap;
    }
}

This will be creating a single map for all the attributes in my POJO.

What I want is have this POJO converted to 3 different maps(which essentialy are fields of a DynamoDB) I can either define 3 POJOs indivdually and use ObjectMapper on each of them separately, or is there some other way to do it where all fields remain in one POJO only?

I explored mapStruct(https://mapstruct.org/) couldn’t get much out of it. Thoughts?

Answer

You can create methods to get required maps.

public class Test {

    public static void main(String[] args) {
        Person person = new Person("Foo", "Bar", "1", "99999", "[email protected]");

        System.out.println(person.getNameMap());
        System.out.println(person.getIdMap());
        System.out.println(person.getContactMap());
    }
}

@AllArgsConstructor
class Person {
    private String firstName;
    private String lastName;
    private String id;
    private String mobileNumber;
    private String email;

    public HashMap<String, Object> getNameMap() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("firstName", this.firstName);
        map.put("lastName", this.lastName);
        return map;
    }

    public HashMap<String, Object> getIdMap() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", this.id);
        return map;
    }

    public HashMap<String, Object> getContactMap() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("mobileNumber", this.mobileNumber);
        map.put("email", this.email);
        return map;
    }
}