繁体   English   中英

地图获取方式<String,List<Data> &gt; 从 yaml 使用snakeyaml

[英]how to get Map<String,List<Data>> from yaml using snakeyaml

尝试从 yaml 加载数据并创建以下对象:

问题:无法将 yaml 映射到对象,当我尝试它时总是抛出异常:java.util.LinkedHashMap 无法转换为 com.heraizen.DataConfig$Data

Map<String,List<Data>> map;

代码片段:

public class DataConfig {
private Map<String, List<Data>> heros = new HashMap<String, List<Data>>();

public static class Data {
    private String name;
    private String uri;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    @Override
    public String toString() {
        return "Data [name=" + name + ", uri=" + uri + "]";
    }

}

public Map<String, List<Data>> getHeros() {
    return heros;
}

public void setHeros(Map<String, List<Data>> heros) {
    this.heros = heros;
}

yaml:

  --- 
 heros: 
   one:

     - name: h1
       url: hu2
     - name: h2
       url: hu22
  two: 
    - name: h3
      url: hu3

构造对象:

   Yaml yaml = new Yaml(new Constructor(DataConfig.class));

   DataConfig retValue = (DataConfig) yaml.load(new FileInputStream("one.yaml"));
   retValue.getHeros().entrySet().forEach(ele->{
       System.out.println(ele.getKey()+" "+ele.getValue().get(0).getName());
   });
    System.out.println(retValue);

由于DataConfig不是LinkedHashMap的子类型或超类型,因此无法在其中使用强制转换。 我不熟悉yaml,但是我可以假设方法yaml.load()从您的异常描述中返回LinkedHashMap

尝试编写属于DataConfig的静态方法,该方法将LinkedHashMap转换为DataConfig

public static DataConfig parseNew(LinkedHashMap map) {

}

为了解决这个问题,你应该在你的Yaml对象中添加一个TypeDescription并手动映射底层属性列表的类型:

yaml.addTypeDescription(new TypeDescription(DataConfig.class) {
    @Override
    public boolean setupPropertyType(String key, Node valueNode) {
        if ("heros".equals(key) &&  valueNode instanceof MappingNode) {
            MappingNode mappingNode = (MappingNode) valueNode;
            boolean listTypeDefined = false;
            for (NodeTuple nodeTuple : mappingNode.getValue()) {
                if (nodeTuple.getValueNode() instanceof SequenceNode) {
                    SequenceNode sequenceNode = (SequenceNode) nodeTuple.getValueNode();
                    sequenceNode.setListType(Data.class);
                    listTypeDefined = true;
                }
            }
            return listTypeDefined;
        }
        return super.setupPropertyType(key, valueNode);
    }
});

如果你这样做并运行你的程序,你应该看到以下输出:

one h1
two h3
Test$DataConfig@6a79c292

请注意您的示例中的一个小错误,您的Data类有一个属性url而在 yaml 中它是uri

暂无
暂无

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

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