解析来自YAML文件的对象列表

时间:2019-01-12 13:51:54

标签: java yaml

我正在尝试将Yaml文件解析为对象列表,但出现以下错误。

Method threw 'com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException' exception.

我的Java代码:

public class ViewResultsModel
{
   @JsonProperty
   List<FileModel> files;

   public ViewResultsModel()
   {
   }

   public ViewResultsModel(List<FileModel> files)
   {
      this.files = files;
   }
 // getters and setters omitted
}


public class FileModel
{
   @JsonProperty
   String fileType;
   @JsonProperty
   String destination;
   @JsonProperty
   String filePath;
 // getters and setters omitted
}


public static void main(String[] args) throws IOException
   {
      File file = new File("Template.yaml");
      final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); // jackson databind
      mapper.readValue(file, ViewResultsModel.class);
   }

YAML文件:

file:
  fileType: TXT
  fileDestination: there
  filePath: C:/

file:
  fileType: PDF
  fileDestination: here
  filePath: C:/

我想阅读Yaml并创建FileModel对象列表

2 个答案:

答案 0 :(得分:0)

您在下面的行中指定了ViewResultsModel类:

mapper.readValue(file, ViewResultsModel.class);

但是您要映射的实际字段在您的FileModel类中

答案 1 :(得分:0)

您的YAML对象具有Java类不知道的成员fileDestination。代替

@JsonProperty
String destination;

尝试

@JsonProperty("fileDestination")
String destination;

顺便说一句,您输入的内容不是合法的YAML。您两个项目名称为file,其中只有一个可能。您要建立清单吗?

相关问题