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