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

时间:2014-10-24 21:08:15

标签: java mapping jackson 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;
}

有没有简单的方法呢?什么库在这里有用?

感谢。

1 个答案:

答案 0 :(得分:2)

也许http://dozer.sourceforge.net可以帮到你。它是一个可由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看起来像这样:

<?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属性。也许你可以看到错误并使用代码片段。也许这是Dozer中的一个错误......我找不到使用this[0]的任何示例。