将列表<map<string,object>> 转换为 POJO class 的对象

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

我有一个 HashMap 对象列表,其中 hashMap 对象包含 属性 名称作为键和 属性 的值作为值列表>。如何将这些 HashMap 对象中的每一个转换为我的 POJO class 的对象??

下面是如何使用 reflection:

波乔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;
    }
}

使用反射填充 pojo 的实例;

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

输出:

This is my text value. 10

This is my second text value. 20