我正在尝试用SnakeYaml在Java语言中解析一个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。我不明白为什么它不使用JavaBean :我的Report类对我来说似乎是一个合法的setter。
我还遗漏了什么吗?
发布于 2019-10-30 14:43:16
mainSourceFile应为MainSourceFile。
https://stackoverflow.com/questions/48964287
复制相似问题