2014-03-12 282 views
4

說我有這樣一個YAML文件的列表,反序列化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庫。

回答

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