首页 > 代码库 > java 实现将java对象转为yaml文件

java 实现将java对象转为yaml文件

首先我们建两个类,以下两个类展示的是一个学生拥有多个手机号码联系人.

先是学生类:

package com.ming.yaml.beans;import java.util.ArrayList;import java.util.List;/** * 学生类 * @author ming * */public class Student {    private int id;        private String name;        private int age;        //一个学生有多个电话号码    List<Tel> tels=new ArrayList<Tel>();    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public List<Tel> getTels() {        return tels;    }    public void setTels(List<Tel> tels) {        this.tels = tels;    }        }

 

然后是联系人:

package com.ming.yaml.beans;/** * 联系人电话类 * @author ming * */public class Tel {    private String name;        private String tel;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getTel() {        return tel;    }    public void setTel(String tel) {        this.tel = tel;    }                }

测试代码:

package com.ming.yaml;import java.io.FileWriter;import java.util.ArrayList;import java.util.List;import org.yaml.snakeyaml.Yaml;import com.ming.yaml.beans.Student;import com.ming.yaml.beans.Tel;/** *  * @author ming * */public class Test1 {    public static void main(String[] args) throws Exception{        Student stu=new Student();        stu.setName("路飞");        stu.setAge(24);        stu.setId(1);        Tel t=new Tel();        t.setName("张三");        t.setTel("10123041445");        Tel t1=new Tel();        t1.setName("李四");        t1.setTel("19923041455");        List<Tel> tels=new ArrayList<Tel>();        tels.add(t);        tels.add(t1);        stu.setTels(tels);        Yaml yaml = new Yaml();        yaml.dump(stu, new FileWriter("stu.yaml"));            }}

最后产生的stu.yaml文件的代码如下:

!!com.ming.yaml.beans.Studentage: 24id: 1name: 路飞tels:- {name: 张三, tel: ‘10123041445‘}- {name: 李四, tel: ‘19923041455‘}

 

java 实现将java对象转为yaml文件