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

我有一个问题。我想使用JAXB将一个对象转换为另一个对象。就像在中,我有一个class com.home.Student和另一个class

com.school.Student,它们都有相同的参数,实际上都是相同的(复制粘贴),但是包不同。我想使用进行它们之间的转换JAXB

怎么做,请帮帮我。

回答:

您可以执行以下操作。

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

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;

}

}

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;

}

}

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;

}

}

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

}

}

以上是 如何使用JAXB序列化和反序列化对象? 的全部内容, 来源链接: utcz.com/qa/400566.html

回到顶部