首页 > 解决方案 > 为什么我在解析 YAML 块时出现此错误?

问题描述

我有这个 YAML 块:

- operationId: "getG"
  applicationName: "c"

- operationId: "get"
  applicationName: "c"

实际上我想用 YAML 的杰克逊库来解析它,我有这个代码:

public class YamlProcessor {

    ListYamlEntries> entries;
}

@Getter //lombok
@Setter //lombok
public class YamlEntries {

    @JsonProperty("applicationName")
    String applicationName;

    @JsonProperty("operationId")
    String operationId;

}
public YamlProcessor yamlParser(String file) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        objectMapper.findAndRegisterModules();
        YamlProcessor yamlEntries = objectMapper.readValue(new File(file), YamlProcessor.class);

        yamlEntries.getEntries().forEach(valuesOfYaml -> {
                log.info("applicationName: " + valuesOfYaml.getApplicationName());
                log.info("operationId: " + valuesOfYaml.getOperationId());

        });

        return yamlEntries;
    }

但我得到这个错误,我不知道为什么:

Cannot deserialize instance of `[....objects.YamlEntries;` out of START_OBJECT token
 at [Source: (File); line: 10, column: 1]

谁能弄清楚并帮助我?

标签: javaspringjacksonyaml

解决方案


我不确切知道您要解析什么,但是您发布的 yaml 应该解析为 a List<YamlEntries>而不是List<Map<String, YamlEntries>>

如果你想创建一个地图列表,你的 yaml 应该是这样的:

 - key1:
     operationId: "getG"
     applicationName: "c"
   key2:
     operationId: "getG"
     applicationName: "c"
    

 - otherkey1:
     operationId: "get"
     applicationName: "c"
   otherkey2:
     operationId: "getG"
     applicationName: "c"

如果您想解析 aList<YamlEntries>这应该适合您。

在yaml中你必须有类似的东西

entries:
  - operationId: "getG"
    applicationName: "c"

  - operationId: "get"
    applicationName: "c"

然后像这样的类将属性映射到 YamlEntries 列表中:

@Component
@ConfigurationProperties(prefix = "entries")
public class Endpoints {
  private List<YamlEntries> yamlEntries;
}

推荐阅读