如何将Yaml文件转换为具有复杂对象通用的列表

时间:2018-07-24 04:08:33

标签: spring yaml snakeyaml

我的Yaml是这样的:

- code: code1
  type: REST
  base-url: https://api.test1.com/api/v1
  endPoints:
    - type: BATCH
      path: /transmissions
      method: POST
      content-type: application/json
      headers: [{key: Authorization, expression: '#root.apiKey'}]
      dependencies: []
      params:
        - key: campaign_id
          source: campaign_id
        - key: subject
          source: subject
- code: code2
  type: SAAS
  base-url: https://api.test2.com/api/v1
  endPoints:
    - type: ONE
      path: /transmissions2
      method: GET
      content-type: application/json
      headers: [{key: Authorization, expression: '#root.apiKey'}]
      dependencies: []
      params:
        - key: campaign_id
          source: campaign_id
        - key: subject
          source: subject
#
...

java通用类:

@Data
public class MappingField {
    private String code;
    private ServiceType type;
    @JsonProperty("base-url")
    private String baseUrl;
    private int port;
    private List<EndPoint> endPoints;
    private Map<String, EndPoint> endPointMapByType = new HashMap<>();

    @Data
    public static class EndPoint {
        private EndpointType type;
        private String path;
        @JsonProperty("content-type")
        private String contentType;
        private HttpMethod method;
        @JsonProperty("substitution_data")
        private List<String> substitutionData;
        private List<Map<String,Object>> headers;
        private List<Map<String,Object>> params;
        private Map<String,Object> response;
    }
}

我使用snakeYaml对此文档进行解析,如下所示:请参见https://bitbucket.org/asomov/snakeyaml/wiki/Documentation#markdown-header-type-safe-collections

@Test
public void test4(){
    Constructor constructor = new Constructor(List.class);//Car.class is root
    TypeDescription carDescription = new TypeDescription(List.class);
   // carDescription.putListPropertyType("null",MappingField.class);
    constructor.addTypeDescription(carDescription);
    Yaml yaml = new Yaml(constructor);
    final Object load = 
    yaml.load(this.getClass().getClassLoader().getResourceAsStream("test1.yml"));

    assertNotNull("load");
}

当它运行时,它返回List<Object>,我该怎么做才能让它返回List<MappingField>? 如何将Java泛型“ MappingFields”添加到列表集合中?

注意:我的Yaml根是列表

1 个答案:

答案 0 :(得分:0)

final List<MappingFields> load = 
(List<MappingFields>) yaml.load(this.getClass().getClassLoader().getResourceAsStream("test1.yml"));

如果在YAML中添加了额外的标记,则可以使用

- !!your.package.MappingFields
  code: code1
...