我尝试使用snakeyaml
lib解析Yaml文件。这是我的yaml文件。
---
users:
- name: Bobby
status: single
license: no
- name: Timmy
status: single
license: no
available: yes
和Java代码。
public class Users {
private List<User> users;
// getters/setters/def constructor have omitted
}
用户类。
public class User {
private String name;
private String status;
private String license;
private String available;
// getters/setters/def constructor have omitted
}
我的解析内容的代码。
Constructor constructor = new Constructor(Users.class);
TypeDescription usersDescription = new TypeDescription(Users.class);
profileDescription.putListPropertyType("users", User.class);
constructor.addTypeDescription(usersDescription);
Yaml yml = new Yaml(constructor);
Users users = (Users) yml.load(new FileInputStream(new File("/path/file.yaml")));
但我有一个例外。
Exception in thread "main" Cannot create property=users for JavaBean=Users(users=null)
in 'reader', line 1, column 1:
users:
^
我该如何解决?
PS 的
当我尝试使用两个用户转储内容时
!!com.project.model.Users
users:
- {}
- {}
答案 0 :(得分:0)
试试这个:
Users users= (Users) yaml.loadAs(new FileInputStream(new File("/path/file.yaml")), Users.class);
而不是:
Constructor constructor = new Constructor(Users.class);
TypeDescription usersDescription = new TypeDescription(Users.class);
profileDescription.putListPropertyType("users", User.class);
constructor.addTypeDescription(usersDescription);
Yaml yml = new Yaml(constructor);
Users users = (Users) yml.load(new FileInputStream(new File("/path/file.yaml")));