使用 jackson databind 解析 yaml 导致 MismatchedInputException
Parsing yaml using jackson databind causes MismatchedInputException
我尝试读取的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 文件对象提供,而不是将其内容作为字符串提供。结果保持不变。我错过了什么?
yaml 结构应该有 items
array/list
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
和其他 class 没有 args 构造函数,否则在 ObjectMapper
上设置适当的标志
我尝试读取的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 文件对象提供,而不是将其内容作为字符串提供。结果保持不变。我错过了什么?
yaml 结构应该有 items
array/list
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
和其他 class 没有 args 构造函数,否则在 ObjectMapper