将yaml反序列化为对象列表

时间:2014-03-12 12:33:18

标签: java snakeyaml

假设我有一个像这样的Yaml文件,

people:
- name         : Joe
  surname    : Barber
  age : 16
- name         : Andy
  surname    : Lots
  age : 17

我有一个这样的课程,

public class people {
    private String name;
    private String surname;
    private String age;

<!-- With getters and setters -->
}

我如何从Yaml文件中获取人物对象列表? 只是从文件中的键获取值非常简单,但将其映射到对象集合则不是。 我正在使用snakeYaml lib。

1 个答案:

答案 0 :(得分:6)

我希望这可以帮到你。

public class StackOverflow {

public static void main(String[] args) {
    final URL resource = StackOverflow.class.getResource("people.yaml");
    final Constructor peopleContructor = new Constructor(Group.class);
    final TypeDescription peopleDescription = new TypeDescription(People.class);
    peopleDescription.putMapPropertyType("people", People.class, Object.class);
    peopleContructor.addTypeDescription(peopleDescription);

    final Yaml yaml = new Yaml(peopleContructor);
    try {
        final Group group = (Group) yaml.load(resource.openStream());
        for (final People people : group.getPeople()) {
            System.out.println(people);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static class People {
    private String name;
    private String surname;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "People: {name: " + this.name + ", surname: " + this.surname + ", age: " + this.age + "}";
    }
}
public static class Group {
    private List<People> people;

    public List<People> getPeople() {
        return people;
    }

    public void setPeople(List<People> people) {
        this.people = people;
    }
}}