使用 Dozer 转换嵌套集合
我有一个类 A,它有一个类 B 的嵌套集:
public class A {
private Set<B> children;
}
public class B {
private int value;
}
我还有一个类 C,它有一个类 D 的嵌套集:
public class C {
private Set<D> children;
}
public class D {
private int value;
}
现在给定一个 A 列表,如何将其转换为 C 列表?理想情况下,我不必提供任何映射提示,因为我使用的是泛型。例如:
List<A> src = new ArrayList<A>();
// ----- Add some A's to src -----
List<C> dst = mapper.map(src, List<C>.class);
显然,最后一行的语法不正确。应该是什么?另外,我如何告诉 Dozer 要创建什么类型的列表或集合?
谢谢。
纳雷什
I have a class A which has a nested set of class B:
public class A {
private Set<B> children;
}
public class B {
private int value;
}
I also have a class C which has a nested set of class D:
public class C {
private Set<D> children;
}
public class D {
private int value;
}
Now given a List of A, how do I convert it to a List of C? Ideally I should not have to supply any mapping hints since I am using generics. For example:
List<A> src = new ArrayList<A>();
// ----- Add some A's to src -----
List<C> dst = mapper.map(src, List<C>.class);
Obviously, the syntax of last line is not correct. What should it be? Also how do I tell Dozer what type of a List or a Set to create?
Thanks.
Naresh
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这实际上在他们的常见问题解答中得到了回答,但由于某种原因它一直在高级部分中。我不认为这是一个高级话题,我认为这是一个常见的事情。 您可以使用集合提示来完成此操作。
该答案向您展示了如何在 xml 中执行此操作。以下是如何使用映射在 java 代码中完成此操作:
提示告诉 dozer,“这个 A 列表应该转换为 JsonName 实例列表”。以下是将此映射添加到映射器的方法:
This is actually answered in their FAQ, but it's all the way down in the advanced section for some reason. I don't think this is an advanced topic, I think it's a common thing to want to do. You do it with a collection hint.
That answer shows you how to do it in xml. Here's how you can do it in java code with a Mapping:
The hint tells dozer, "this list of A's should be converted to a list JsonName instances". Here's how you add this mapping to your mapper:
您应该简单地扩展此列表转换。 Dozer 转换 JavaBean 和此类对象,而不是集合。因此,如果您想传递集合,您可以创建一个包装器,例如
注意:此代码使用 Guava。
You should simply expand this list convertion. Dozer convert JavaBeans and such objects, not collections. So, if you want to pass collections, you can create a wrapper like
Note: This code use Guava.