java convert list of object array to a POJO

◇◆丶佛笑我妖孽 提交于 2019-12-23 04:36:57

问题


How to convert

List<Object[]> to List<POJOObject>

Here is example

//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?

Thanks.


回答1:


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

I tried it shortly with this:

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

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>

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].



来源:https://stackoverflow.com/questions/26556298/java-convert-list-of-object-array-to-a-pojo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!