将 yaml 数组映射到 java 对象

Mapping yaml array to java object

我如何将以下 yaml 数据映射到 java pojo

 - messageId: A
   category: A
   severity: A

 - messageId: B
   category: B 
   severity: B

数组将包含多个元素

public class Message {
    private String messageID;
    private String category;
    private String severity;
}

public class MessageDefinitionList {
    private ArrayList<Message> msgDefinition;
}

以下对象映射器代码对我不起作用,returns null

MessageDefinitionList msgDefinitionList = mapper.readValue(mapper.writeValueAsString(yaml.load(file)), MessageDefinitionList.class);

这会起作用:

msg.yml

msgDefinition:
- messageId: A
  category: A
  severity: A
- messageId: B
  category: B
  severity: B

POJOs(lombok注解,查看字段名与YAML中的对应)

@Data
class Message {
    private String messageId;
    private String category;
    private String severity;
}

@Data
class MessageDefinitionList {
    private List<Message> msgDefinition;
}

与 Jackson 的映射(您也可以使用 StringInputStream 代替 File 参数):

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
MessageDefinitionList result = mapper.readValue(new File("src/main/resources/msg.yml"), MessageDefinitionList.class);

Jackson YAML maven 依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.13.0</version>
</dependency>