首页 > 解决方案 > 从 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 对象列表

标签: javayaml

解决方案


你的 YAML 对象有一个fileDestination你的 Java 类不知道的成员。代替

@JsonProperty
String destination;

尝试

@JsonProperty("fileDestination")
String destination;

顺便说一句,您的输入不是合法的 YAML。你有两个项目名称file,只有一个是可能的。你想建立一个列表吗?


推荐阅读