Yaml
文件包含:
test:
subHeading: "1234"
Model.java
class Model{
@JsonProperty("test")
private SubHeading subHead;
private class SubHeading{
@JsonProperty("subHeading")
private String text;
}
我尝试按以下方式解析上述Yaml
内容:
Yaml yaml = new Yaml(new Constructor(Model.class));
System.out.println(yaml.load(new FileReader(PATH)).toString());
我立即得到一个例外:
Cannot create property=test for JavaBean=Model@13a5fe33
in 'reader', line 1, column 1:
test:
有什么主意我做错了什么,我可以在这里改变什么?
答案 0 :(得分:0)
所有拳头都使用Jackson
注释,但使用SnakeYaml
库读取yaml
文件。您必须通过以下方式简化解决方案:
Jackson
Jackson
注释。 模型
在新文件中将每个类创建为public class
。
public class Model {
private SubHeading test;
public SubHeading getTest() {
return test;
}
public void setTest(SubHeading test) {
this.test = test;
}
@Override
public String toString() {
return "Model{" +
"test=" + test +
'}';
}
}
和
public class SubHeading {
private String subHeading;
public String getSubHeading() {
return subHeading;
}
public void setSubHeading(String subHeading) {
this.subHeading = subHeading;
}
@Override
public String toString() {
return "SubHeading{" +
"subHeading='" + subHeading + '\'' +
'}';
}
}
用法示例:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
public class YamlTest {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String text = "test:\n" +
" subHeading: \"1234\"";
Model model = mapper.readValue(text, Model.class);
System.out.println(model);
}
}
以上打印:
Model{test=SubHeading{subHeading='1234'}}