java jaxb序列化 空值_如何使用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 code;

Status(String code) {

this.code = code;

}

public String getCode() {

return code;

}

}

普通学校学生

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

Status(String code) {

this.code = code;

}

public String getCode() {

return code;

}

}

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 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 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());

}

}

2020-09-21

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值