java - 将 list<map<string,object>> 转换为 POJO 类的对象

标签 java arraylist hashmap pojo

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

最佳答案

以下是如何使用reflection来做到这一点:

Pojo 类:

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

关于java - 将 list<map<string,object>> 转换为 POJO 类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28496684/

相关文章:

java - 从同一类创建对象时会保存哪些值

javascript - 在 JS 中使用 "in"关键字和映射

scala - LinkedHashMap 更改为 HashMap 并在 flink 数据流算子中崩溃

java - 如何在 Spring-boot 中为 REST API 的每个请求创建唯一的 ID?

android - 使用 Parcelable 通过 Intent 传递 ArrayList 时出现 NullPointerException

java - 在 Android 中显示图像网格,网格布局中心为空?

xml - Xstream错误

java - 如何使用 HashMap 计算数字对的绝对差?

java - 如何从java代码中获取控制台命令的结果?

java - OpenCV 4.1 Java -contourArea() 断言深度 == CV_32F || 失败船体矩阵的深度 == CV_32S