Convert a Map to POJO in Java

How do I convert a Map object to my other plain old Java object (POJO) without going into loops and having to write a class using Java reflection, or some other?

ANSWER

Well, yes, reflection is one but you didn’t want to do that yourself. For some good reason, I bet. It’s a good exercise if you have all the time in the world. But when faced with deadlines and having to write Unit tests for a whole class you wrote, there must be an easier way.

There is more than one way, but what I normally use is the Jackson ObjectMapper. Yes, the same one from the com.fasterxml.jackson library.

Anyway, with ObjectMapper it is pretty straightforward to do so. If I have a Person class like this:

    public class Person {
        private String firstName;
        private String lastName;
    }

My Map object will look like this:

        Map<String, Object> map = new HashMap<>();
        map.put("firstName", "Johnny");
        map.put("lastName", "Foo");

Then with ObjectMapper one can simply do this:

        ObjectMapper mapper = new ObjectMapper();
        Person person = mapper.convertValue(map, Person.class);

Alternatively, the keys in the Map may not align with the fields in the Person class. Well, I usually encounter this when working with JSON objects with lots of crazy looking field names. Something like this – NZT_Mor_First_Name__c – which I clearly don’t want my class field name to be like.

Well, we can use @JsonProperty annotation which is part of Jackson by the way and assign that our class field. The Person class will now look like:

    public class Person {

        @JsonProperty("NZT_Mor_First_Name__c")
        private String firstName;

        @JsonProperty("NZT_Mor_Last_Name__c")
        private String lastName;
    }

Again the Map will hold these values:

        Map<String, Object> map = new HashMap<>();
        map.put("NZT_Mor_First_Name__c", "Jose");
        map.put("NZT_Mor_Last_Name__c", "Yamut");

Now it will map out those weird looking key names to its corresponding class fields.

One thing to note is you might need to set ObjectMapper features such as ignoring unknown properties and make it case insensitive. Allow it a bit more room to wiggle, wiggle.

        ObjectMapper mapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES);