JAXB之xml与javabean的相互转换

1.JAXB常用注解

(1)@XmlRootElement

@XmlRootElement用于类级别的注解,对应xml的根元素,常与 @XmlType 和 @XmlAccessorType一起使用。

 

(2)@XmlType

@XmlType用在class类的注解,常与@XmlRootElement,@XmlAccessorType一起使用。它有三个属性:name、propOrder、namespace,其中propOrder属性用来指定序列成的xml节点顺序,在使用@XmlType的propOrder 属性时,必须列出JavaBean对象中的所有属性,否则会报错。

 

(3)@XmlAccessorType

@XmlAccessorType用于指定由java对象生成xml文件时对java对象属性的访问方式。常与@XmlRootElement、@XmlType一起使用。它的属性值是XmlAccessType的4个枚举值,分别为:

  XmlAccessType.FIELD:java对象中的所有成员变量

  XmlAccessType.PROPERTY:java对象中所有通过getter/setter方式访问的成员变量

  XmlAccessType.PUBLIC_MEMBER:java对象中所有的public访问权限的成员变量和通过getter/setter方式访问的成员变量

  XmlAccessType.NONE:java对象的所有属性都不映射为xml的元素

  注意:@XmlAccessorType的默认访问级别是XmlAccessType.PUBLIC_MEMBER,因此,如果java对象中的private成员变量设置了public权限的getter/setter方法,就不要在private变量上使用@XmlElement和@XmlAttribute注解,否则在由java对象生成xml时会报同一个属性在java类里存在两次的错误。同理,如果@XmlAccessorType的访问权限为XmlAccessType.NONE,如果在java的成员变量上使用了@XmlElement或@XmlAttribute注解,这些成员变量依然可以映射到xml文件。

 

(4)@XmlElement

@XmlElement将java对象的属性映射为xml的节点,在使用@XmlElement时,可通过name属性改变java对象属性在xml中显示的名称。

 

(5)@XmlAttribute

@XmlAttribute用于把java对象的属性映射为xml的属性,并可通过name属性为生成的xml属性指定别名。

 

(6)@XmlTransient

@XmlTransient用于标示在由java对象映射xml时,忽略此属性。即,在生成的xml文件中不出现此元素。

 

(7)@XmlJavaTypeAdapter

@XmlJavaTypeAdapter常用在转换比较复杂的对象时,如map类型或者格式化日期等。使用此注解时,需要自己写一个adapter类继承XmlAdapter抽象类,并实现里面的方法。

 

2.案例

@XmlType(propOrder={"id","name","age","birthday","teacherList","teacher","data","dataList"}) //指定序列成的xml节点顺序
@XmlAccessorType(value=XmlAccessType.FIELD)  //访问类型改为字段
@XmlRootElement   //根元素
public class Student {

    @XmlElement   //子元素
    private String id;

    @XmlElement
    private String name;

    @XmlElement
    private Integer age;

    @XmlElement
    @XmlJavaTypeAdapter(DateAdapter.class)
    private Date birthday;

    @XmlElementWrapper(name = "teacherList")
    @XmlElement(name= "teacher")
    private List teacherList;

    @XmlElement
    private Teacher teacher;

    @XmlElement
    @XmlJavaTypeAdapter(MapAdapter.class)
    private Map data;

    @XmlElement
    @XmlJavaTypeAdapter(MapListAdapter.class)
    private List> dataList;

    @XmlAttribute  //Student根元素属性
    private Integer sex;

    @XmlTransient  //该属性不加入序列化/反序列化中
    private Float weight;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public List getTeacherList() {
        return teacherList;
    }

    public void setTeacherList(List teacherList) {
        this.teacherList = teacherList;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public Map getData() {
        return data;
    }

    public void setData(Map map) {
        this.data = map;
    }

    public Integer getSex() {
        return sex;
    }

    public void setSex(Integer sex) {
        this.sex = sex;
    }

    public Float getWeight() {
        return weight;
    }

    public void setWeight(Float weight) {
        this.weight = weight;
    }

    public List> getDataList() {
        return dataList;
    }

    public void setDataList(List> dataList) {
        this.dataList = dataList;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", teacherList=" + teacherList +
                ", teacher=" + teacher +
                ", data=" + data +
                ", dataList=" + dataList +
                ", sex=" + sex +
                ", weight=" + weight +
                '}';
    }

}

 

@XmlAccessorType(value=XmlAccessType.FIELD)
@XmlType(propOrder={"id","name","age"})
public class Teacher {

    @XmlElement
    private String id;
    @XmlElement
    private String name;
    @XmlElement
    private Integer age;

    public Teacher() {

    }

    public Teacher(String id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

 

/**
 * 自定义时间适配器类
 */
public class DateAdapter extends XmlAdapter {
    @Override
    public Date unmarshal(String str) throws Exception {
        SimpleDateFormat sdf = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return str == null ? null : sdf.parse(str);
    }

    @Override
    public String marshal(Date date) throws Exception {
        SimpleDateFormat sdf = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return date == null ? null : sdf.format(date);
    }

    private SimpleDateFormat getSimpleDateFormat(String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf;
    }
}

 

@XmlType(propOrder = {"key", "value"})
@XmlAccessorType(value=XmlAccessType.FIELD)
public class Entry {

    @XmlAttribute
    private String key;

    @XmlValue
    private String value;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

 

@XmlAccessorType(value=XmlAccessType.FIELD)
public class MapConvertor {
    @XmlElement(name="result")
    public List entryList = new ArrayList<>();
}

 

public class MapAdapter extends XmlAdapter> {

    @Override
    public Map unmarshal(MapConvertor mapConvertor) throws Exception {
        Map map = new HashMap<>();
        if (mapConvertor != null) {
            List entryList = mapConvertor.entryList;
            for (Entry entry : entryList) {
                map.put(entry.getKey(), entry.getValue());
            }
            return map;
        }

        return null;
    }

    @Override
    public MapConvertor marshal(Map map) throws Exception {
        MapConvertor mapConvertor = new MapConvertor();
        if (map != null) {
            for (Map.Entry entry : map.entrySet()) {
                Entry en = new Entry();
                en.setKey(entry.getKey());
                en.setValue(entry.getValue());
                mapConvertor.entryList.add(en);
            }
            return mapConvertor;
        }

        return null;
    }
}

 

@XmlAccessorType(value=XmlAccessType.FIELD)
public class MapListConvertor {
    @XmlElement(name="resultList")
    public List mapList = new ArrayList<>();
}

 

public class MapListAdapter extends XmlAdapter>> {

    private MapAdapter mapAdapter = new MapAdapter();

    @Override
    public List> unmarshal(MapListConvertor mapListConvertor) throws Exception {
        List> mapList = new ArrayList<>();
        if (mapListConvertor != null) {
            List list = mapListConvertor.mapList;
            for (MapConvertor mapConvertor : list) {
                Map map = this.mapAdapter.unmarshal(mapConvertor);
                mapList.add(map);
            }
            return mapList;
        }

        return null;
    }

    @Override
    public MapListConvertor marshal(List> mapList) throws Exception {
        MapListConvertor mapListConvertor = new MapListConvertor();
        if (mapList != null) {
            for (Map map : mapList) {
                MapConvertor mapConvertor = this.mapAdapter.marshal(map);
                mapListConvertor.mapList.add(mapConvertor);
            }
            return mapListConvertor;
        }

        return null;
    }
}

 

public class Main {

    public static void main(String[] args) {
        Student stu = new Student();
        initData(stu);

        try {
            //javabean转换为xml
            JAXBContext context = JAXBContext.newInstance(Student.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            StringWriter writer = new StringWriter();
            marshaller.marshal(stu, writer);
            System.out.println(writer.toString());

            //xml转换为javabean
            JAXBContext context2 = JAXBContext.newInstance(Student.class);
            Unmarshaller unmarshaller = context2.createUnmarshaller();
            String xmlStr = "\n" +
                    "\n" +
                    "    007\n" +
                    "    小西\n" +
                    "    25\n" +
                    "    2018-12-01 16:12:02\n" +
                    "    \n" +
                    "        \n" +
                    "            1\n" +
                    "            小明\n" +
                    "            22\n" +
                    "        \n" +
                    "        \n" +
                    "            2\n" +
                    "            小红\n" +
                    "            22\n" +
                    "        \n" +
                    "        \n" +
                    "            3\n" +
                    "            小志\n" +
                    "            22\n" +
                    "        \n" +
                    "    \n" +
                    "    \n" +
                    "        1\n" +
                    "        佳佳\n" +
                    "        22\n" +
                    "    \n" +
                    "    \n" +
                    "        小罗\n" +
                    "        小嘉\n" +
                    "        小敏\n" +
                    "    \n" +
                    "    \n" +
                    "        \n" +
                    "            小罗\n" +
                    "            小嘉\n" +
                    "            小敏\n" +
                    "        \n" +
                    "        \n" +
                    "            小周\n" +
                    "            小蕾\n" +
                    "        \n" +
                    "    \n" +
                    "";
            Student s = (Student) unmarshaller.unmarshal(new StringReader(xmlStr));
            System.out.println(s.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void initData(Student stu) {
        stu.setId("007");
        stu.setName("小西");
        stu.setAge(25);
        stu.setBirthday(new Date());
        stu.setSex(0);
        stu.setWeight(62.5f);
        //list集合,set集合一样
        ArrayList list = new ArrayList<>();
        list.add(new Teacher("1","小明",22));
        list.add(new Teacher("2","小红",22));
        list.add(new Teacher("3","小志",22));
        stu.setTeacherList(list);
        //在javaBean中添加javaBean
        Teacher teacher = new Teacher("1","佳佳",22);
        stu.setTeacher(teacher);
        //添加map集合
        Map map = new HashMap<>();
        map.put("1", "小罗");
        map.put("2", "小嘉");
        map.put("3", "小敏");
        stu.setData(map);
        //添加map泛型的list
        List> dataList = new ArrayList<>();
        Map map2 = new HashMap<>();
        map2.put("1", "小周");
        map2.put("2", "小蕾");
        dataList.add(map);
        dataList.add(map2);
        stu.setDataList(dataList);
    }

}

 

你可能感兴趣的:(java)