栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用JAXB序列化和反序列化对象?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用JAXB序列化和反序列化对象?

您可以执行以下操作。

注意:

  • 不需要利用JAXBSource将数据具体化为XML。
  • 它在对象模型上不需要任何注释。

com.home.Student

package com.home;public class Student {    private String name;    private Status status;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Status getStatus() {        return status;    }    public void setStatus(Status status) {        this.status = status;    }}

com.home.Status

package com.home;public enum Status {    FULL_TIME("F"),    PART_TIME("P");    private final String pre;    Status(String pre) {        this.pre = pre;    }    public String getCode() {        return pre;    }}

普通学校学生

package com.school;public class Student {    private String name;    private Status status;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Status getStatus() {        return status;    }    public void setStatus(Status status) {        this.status = status;    }}

com.school.Status

package com.school;public enum Status {    FULL_TIME("F"),    PART_TIME("P");    private final String pre;    Status(String pre) {        this.pre = pre;    }    public String getCode() {        return pre;    }}

com.example.Demo;

package com.example;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBElement;import javax.xml.bind.Unmarshaller;import javax.xml.bind.util.JAXBSource;import javax.xml.namespace.QName;public class Demo {    public static void main(String[] args) throws Exception {        com.home.Student studentA = new com.home.Student();        studentA.setName("Jane Doe");        studentA.setStatus(com.home.Status.FULL_TIME);        JAXBContext contextA = JAXBContext.newInstance(com.home.Student.class);        JAXBElement<com.home.Student> jaxbElementA = new JAXBElement(new QName("student"), com.home.Student.class, studentA);        JAXBSource sourceA = new JAXBSource(contextA, jaxbElementA);        JAXBContext contextB = JAXBContext.newInstance(com.school.Student.class);        Unmarshaller unmarshallerB = contextB.createUnmarshaller();        JAXBElement<com.school.Student> jaxbElementB = unmarshallerB.unmarshal(sourceA, com.school.Student.class);        com.school.Student studentB = jaxbElementB.getValue();        System.out.println(studentB.getName());        System.out.println(studentB.getStatus().getCode());    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437692.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号