简体   繁体   English

Dozer,如何将地图转换为复杂类型列表

[英]Dozer, how to convert a map to a list of complex types

I am struggling with a Dozer mapping. 我正在努力使用Dozer映射。 I would like to convert a java.util.Map to a java.util.List<Code> . 我想将java.util.Map转换为java.util.List<Code> My classes are implemented as follows. 我的课程实现如下。

public class A {
   private List<Code> values;
}

class B {
   private Map<String, String> values;
}

class Code {
   private String key;
   private String value;

   // getter & setter ommitted
}

My mapping looks as follows. 我的映射如下所示。

<mapping wildcard="true">
    <class-a>A</class-a>
    <class-b>B</class-b>

    <field custom-converter="ABCustomConverter">
        <a>values</a>
        <b>values</b>
    </field>
</mapping>

The custom converter. 自定义转换器。

public class ABCustomConverter extends DozerConverter<List<Code>, Map<String, String>> {

     public ABCustomConverter () {
       super((Class<List<Code>>) (Class<?>) List.class, (Class<Map<String, String>>) (Class<?>) List.class);
     }

     @Override
     public Map<String, String> convertTo(List<Code> source, Map<String, String> destination) {
        throw new NotImplementedException();
     }

     @Override
     public List<Code> convertFrom(Map<String, String> source, List<Code> destination) {

        if (source == null) return null;

        List<Code> modelList = Lists.newArrayListWithCapacity(source.size());

        for (String key : source.keySet()) {
          Code model = new Code();
          model.setKey(key);
          model.setValue(source.get(key));

          modelList.add(model);
        }
        return modelList;
     }
}

My custom converter always receives a null value when convertForm is called. 调用convertForm时,我的自定义转换器始终接收null值。 For some reason Dozer tries to get the key values from my java.util.Map and this results, as expected, in a null value that is forwarded to my custom converter. 出于某种原因,推土机试图拿到钥匙values从我java.util.Map ,这导致,如预期,在一个null被转发到我的自定义转换器的价值。 But I would like to get the whole map forwarded to my converter. 但我想将整个地图转发给我的转换器。 Can someone explain me how to achieve this custom mapping? 有人可以解释我如何实现这个自定义映射?

The answer is to provide some hints for Dozer. 答案是为Dozer提供一些提示。

<mapping wildcard="true">
    <class-a>A</class-a>
    <class-b>B</class-b>

    <field custom-converter="ABCustomConverter">
        <a>values</a>
        <b>values</b>

        <a-hint>java.util.LinkedHashMap</a-hint>
        <b-hint>java.util.ArrayList</b-hint>
    </field>
</mapping>

Thank you for helping me out! 谢谢你帮助我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM