Search code examples
javaarraylisthashmappojo

convert list<map<string,object>> to object of a POJO class


I have a List of HashMap objects in which hashMap object contains property name as key and value of property as value list>. How to convert each of these HashMap object into an object of my POJO class.??


Solution

  • Here is how you can do it using reflection:

    Pojo class:

    public class MyPojo {
        private String text;
        private Integer number;
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        public Integer getNumber() {
            return number;
        }
    
        public void setNumber(Integer number) {
            this.number = number;
        }
    }
    

    Populate instances of your pojo using reflection;

    final List<Map<String, Object>> objects = new ArrayList<Map<String, Object>>();
    objects.add(new HashMap<String, Object>());
    objects.get(0).put("text", "This is my text value.");
    objects.get(0).put("number", 10);
    objects.add(new HashMap<String, Object>());
    objects.get(1).put("text", "This is my second text value.");
    objects.get(1).put("number", 20);
    
    ArrayList<MyPojo> pojos = new ArrayList<MyPojo>();
    
    for (Map<String, Object> objectMap : objects) {
        MyPojo pojo = new MyPojo();
        for (Entry<String, Object> property : objectMap.entrySet()) {
            Method setter = MyPojo.class.getMethod("set" + property.getKey().substring(0, 1).toUpperCase()
                    + property.getKey().substring(1), property.getValue().getClass());
            setter.invoke(pojo, property.getValue());
        }
        pojos.add(pojo);
    }
    
    for (MyPojo pojo : pojos) {
        System.out.println(pojo.getText() + " " + pojo.getNumber());
    }
    

    Output:

    This is my text value. 10

    This is my second text value. 20