我要阅读的Yaml格式如下
- name: storage
scm: git
src: git+https://bitbucket.org/cer/linux_storage_jenkins.git
version: '5'
- name: linux_jenkins
scm: git
src: git+https://bitbucket.org/cer/linux_jenkins.git
version: '8'
我的模型很简单
public class Requirementsyml {
//setter and getter in place
private List<Requirement> items;
}
public class Requirement {
private String name;
private String scm;
private String src;
private String version;
}
我正在尝试读取yaml内容,如下所示:
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Requirementsyml req = mapper.readValue(yaml_file_content, Requirementsyml.class);
但是我遇到以下异常
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of Requirementsyml out of START_ARRAY token
由于模型具有列表,我认为输入不应该不匹配。 我试图将yaml文件作为java文件对象提供,而不是将其内容作为字符串提供。结果保持不变。我想念什么?
答案 0 :(得分:0)
yaml结构应具有items
数组/列表
items:
- name: storage
scm: git
src: git+https://bitbucket.org/cer/linux_storage_jenkins.git
version: '5'
- name: linux_jenkins
scm: git
src: git+https://bitbucket.org/cer/linux_jenkins.git
version: '8'
否则您可以将其作为要求列表阅读而无需更改yaml
@Test
void test() throws IOException {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
List<Requirement> requirements = mapper.readValue(new File("src/test/resources/requirements.yml"), new TypeReference<List<Requirement>>() {});
assertEquals(2, requirements.size());
}
还要确保Requirement
和其他类没有args构造函数,否则请在ObjectMapper
上设置适当的标志