Java Yaml:如何反序列化集合?
我尝试用Java Yaml:如何反序列化集合?,java,yaml,snakeyaml,Java,Yaml,Snakeyaml,我尝试用snakeyamllib解析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; // ge
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
}
我的代码用于解析内容
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")));
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:
- {}
- {}
试试这个:
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")));