2

我尝试使用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;
    // 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:
    ^

我该如何解决?

附言

当我尝试与两个用户一起转储内容时,我得到

!!com.project.model.Users
users:
- {}
- {}
4

1 回答 1

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")));
于 2015-01-18T14:34:36.150 回答