Dozer,Java:如何将List<List>转换为二维数组?

3
我有一个列表的列表,想用Dozer和自定义转换器将其映射成一个二维数组[][]。
public class Field {
    List<String> items;

    public void add(String s) {
        items.add(s);
    }
}

public class ClassA {
    int anotherVariable;

    List<Field> fields;

    public void add(Field f) {
        fields.add(f);
    }
}

public class ClassB {
    int anotherVariable;

    String[][] itemValues;
}

@Test
public void convertListTo2DArray() {
    Field field1 = new Field();
    field1.add("m"); field1.add("n");

    Field field2 = new Field();
    field2.add("o"); field2.add("p");

    ClassA classA = new ClassA();
    classA.add(field1);  
    classA.add(field2);

    classA.setAnotherVariable(99);

    List<Converter> converters = new ArrayList<Converter>();
    converters.add(new ListToArrayConverter());

    ClassB classB = new DozerBeanMapper().setCustomConverters(converters).map(classA, ClassB.class);  

    /**
     * Result:
     * classB -> anotherVariable = 99
     *
     * classB -> itemValues[][] =
     * ["m", "n"]
     * ["o", "p"]
     */  
}

转换器仅用于在List<List>String[][]之间进行转换,不用于其他变量。
我查看了以下问题的答案,但如果要处理数组而不是Set/List,则应该如何处理自定义转换器? 从HashSet到ArrayList的Dozer映射 任何建议将不胜感激。 谢谢

{btsdaf} - janith1024
{btsdaf} - ThomasMuller
嗨@ThomasMuller,答案有帮助吗? - Ray
1个回答

1

我的Java有点生疏,请容忍我。

如果您希望将转换器仅用于将List转换为String数组而不是其他任何内容,则可以通过在xml中仅为这两个字段指定自定义转换器来限制它的使用方式:

<mapping>
<class-a>beans6.ClassA</class-a>
<class-b>beans6.ClassB</class-b>
<field custom-converter="converter.ConvertListToArray">
    <a>fields</a>
    <b>itemValues</b>
</field>
</mapping>

接下来,在您的Field类中的items属性和ClassA类中的fields属性需要初始化为ArrayList,以防止它们抛出NullPointerException异常。
List<String> items = new ArrayList<String>();
List<Field> fields = new ArrayList<Field>();

最后,这是CustomConverter,假设添加到fields的元素数量始终保持不变:
public class ConvertListToArray implements CustomConverter{
    public Object convert(Object existingDestinationFieldValue, Object sourceFieldValue, 
    Class<?> destinationClass, Class<?> sourceClass) {
        if(sourceFieldValue==null)
            return null;

        if(sourceFieldValue instanceof List && ((List<?>) sourceFieldValue).size()>0){
            List<Field> listOfFields = (List<Field>)sourceFieldValue;

            String[][] destinationValue = new String[2][2];
            for (int i = 0; i<2;i++){
                 Field f = listOfFields.get(i);
                 for (int j = 0;j<f.getItems().size();j++){
                     destinationValue[i][j] = f.getItems().get(j);
                 }
             }
             return destinationValue;

         }
        return null;
    }
}

做得好,非常感谢你的帮助。很抱歉回答晚了,这是无意中的延迟。 - ThomasMuller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接