我正在尝试使用Java中的SnakeYaml解析YAML文件,我正在努力使它通过setter构建我的模型对象。我从SnakeYaml文档中理解的是,当您使用遵循JavaBean规则的对象时,SnakeYaml使用反射来查找setter并使用它们来实现成员。
我将代码缩减到以下简约版本,但它仍然无法正常工作:
这是我的模型对象:
public class Report {
private String MainSourceFile;
public Report() {
super();
}
public String getMainSourceFile() {
return this.MainSourceFile;
}
public void setMainSourceFile(String mainSourceFile) {
this.MainSourceFile = mainSourceFile;
}
}
这是解析YAML文件的代码:
Constructor constructor = new Constructor(Report.class);
Yaml yaml = new Yaml(constructor);
Report report = null;
try (InputStream str = new FileInputStream(file);) {
report = (Report) yaml.load(str);
} catch (FileNotFoundException e) {
throw new ParsingErrorException( String.format("Error while reading export file %s : file not found", file.getAbsolutePath()), e);
} catch (YAMLException e) {
throw new ParsingErrorException(String.format("Error while parsing export file %s", file.getAbsolutePath()), e);
} catch (IOException e1) {
Activator.logWarning(String.format("Error while closing file %s", file.getAbsolutePath()));
}
这是YAML文件:
---
MainSourceFile: /home/user/workspace/project/ex.c
抛出以下错误
Unable to find property 'MainSourceFile' on class: fr.xxx.xxx.model.Report
in 'reader', line 2, column 18:
MainSourceFile: /home/user/workspace/project/ex.c
^
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:268)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.construct(Constructor.java:149)
at org.yaml.snakeyaml.constructor.Constructor$ConstructYamlObject.construct(Constructor.java:308)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObjectNoCheck(BaseConstructor.java:207)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructObject(BaseConstructor.java:196)
at org.yaml.snakeyaml.constructor.BaseConstructor.constructDocument(BaseConstructor.java:161)
at org.yaml.snakeyaml.constructor.BaseConstructor.getSingleData(BaseConstructor.java:147)
at org.yaml.snakeyaml.Yaml.loadFromReader(Yaml.java:524)
at org.yaml.snakeyaml.Yaml.load(Yaml.java:452)
at fr.xxx.xxx.ErrorParser.parseFixesExportFile(ErrorParser.java:116)
... 24 more
Caused by: org.yaml.snakeyaml.error.YAMLException: Unable to find property 'MainSourceFile' on class: fr.xxx.xxx.model.Report
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:189)
at org.yaml.snakeyaml.introspector.PropertyUtils.getProperty(PropertyUtils.java:178)
at org.yaml.snakeyaml.TypeDescription.discoverProperty(TypeDescription.java:240)
at org.yaml.snakeyaml.TypeDescription.getProperty(TypeDescription.java:251)
at org.yaml.snakeyaml.constructor.Constructor$ConstructMapping.constructJavaBean2ndStep(Constructor.java:210)
... 33 more
如果我将MainSourceFile
成员声明为public
,则解析有效(这就是为什么它以大写字母开头)。但我不想让它public
,而且我想使用setter。
我不明白为什么它不使用setter:我的Report
类对我来说似乎是一个合法的JavaBean。
还有什么我遗失的吗?
答案 0 :(得分:0)
MainSourceFile应该是mainSourceFile。