簡體   English   中英

將yaml反序列化為對象列表

[英]Deserialize yaml to list of objects

假設我有一個像這樣的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。

我希望這可以幫到你。

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;
    }
}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM