簡體   English   中英

Dozer,Java:如何從List轉換 <List> 到2D陣列?

[英]Dozer, Java: How to convert from List<List> to 2D Array?

我有一個列表列表,我正在嘗試使用Dozer和Custom Converter映射到二維數組[] []。

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[][]之間的轉換,而不能用於其他變量。

我看了下面問題的答案,但是如何處理Array而不是Custom Converter中的Set / List? 從HashSet到Arraylist的推土機映射

任何建議將不勝感激。 謝謝

我的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屬性初始化為arraylists,以防止它們拋出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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM