java将对象数组列表转换为POJO

java将对象数组列表转换为POJO

本文介绍了java将对象数组列表转换为POJO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何转换

List<Object[]> to List<POJOObject>

这里是例子

//So, lets us say I have Object[], I want to have a class as follows:

class POJOObject {
    //maps to Object[0]
    private Integer x;
    //maps to Object[1]
    private Long y;
    //maps to Object[2]
    private String y;
}

有没有简单的方法可以做到这一点?什么库在这里有用?

Is there any easy way to do that? What library can be useful here?

谢谢.

推荐答案

也许 http://dozer.sourceforge.net

Maybe http://dozer.sourceforge.net can help you. It is a mapping library configurable by xml.

我很快尝试了这个:

public class Main {
  public static void main(String[] args) {
    Object[] obj = new Object[3];
    obj[0] = new Integer(10);
    obj[1] = new Long(2346246234634L);
    obj[2] = "Hello";

    Collections.singletonList("mapping.xml");
    DozerBeanMapper mapper = new DozerBeanMapper(Collections.singletonList("mapping.xml"));
    PojoObject pojo = mapper.map(obj, PojoObject.class);
    System.out.println(pojo);
  }

  public static class PojoObject {
    private Integer integer;
    private Long longg;
    private String string;

    public PojoObject() {}

    public Integer getInteger() {
      return integer;
    }

    public void setInteger(Integer integer) {
      this.integer = integer;
    }

    public Long getLongg() {
      return longg;
    }

    public void setLongg(Long longg) {
      this.longg = longg;
    }

    public String getString() {
      return string;
    }

    public void setString(String string) {
      this.string = string;
    }

    @Override
    public String toString() {
      return String.format("Pojo content: %d, %d, %s", integer, longg, string);
    }
  }
}

我的mappings.xml看起来像这样:

My mappings.xml looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<mappings xmlns="http://dozer.sourceforge.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://dozer.sourceforge.net
      http://dozer.sourceforge.net/schema/beanmapping.xsd">
    <mapping>
        <class-a>java.lang.Object[]</class-a>
    <class-b>ch.romix.dozertest.Main.PojoObject</class-b>
        <field>
        <a>this[0]</a>
        <b>Integer</b>
    </field>
    <field>
        <a>this[1]</a>
        <b>Longg</b>
    </field>
    <field>
        <a>this[2]</a>
        <b>String</b>
    </field>
    </mapping>
</mappings>

不幸的是,它仅将10映射到所有三个PojoObject属性.也许您可以看到错误,并使用代码段作为代码.也许这是推土机中的一个错误...使用this[0]找不到任何示例.

Unfortunately it only mapped 10 to all three PojoObject properties. Maybe you can see the error and use the snippet for your code. Maybe it is a bug in Dozer... I couldn't find any example using this[0].

这篇关于java将对象数组列表转换为POJO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!