Java中JAXB序列化POJO为XML需三步:1. 为POJO添加@XmlRootElement等注解;2. 创建JAXBContext并配置Marshaller;3. 调用marshal方法输出XML,注意JDK11+需引入jakarta.xml.bind依赖。

Java中用JAXB将POJO序列化为XML(即Marshalling)需要三步:添加注解、创建JAXBContext、调用marshal方法。核心是让JAXB知道如何把对象映射成XML结构。
POJO类必须标注red">@XmlRootElement,否则JAXB无法启动序列化。常用注解包括:
示例POJO:
@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {
@XmlElement(required = true)
private String name;
@XmlElement(name = "age")
private int age;
@XmlAttribute
private String id;
// 无参构造函数(JAXB要求)
public Person() {}
public Person(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
}JAXBContext是JAXB操作的入口,需传入POJO类(支持多个类,用逗号分隔)。Marshaller负责执行序列化:
立即学习“Java免费学习笔记(深入)”;
基础代码示例:
Person person = new Person("张三", 28, "P001");
try {
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
// 输出到控制台
marshaller.marshal(person, System.out);
// 或输出到文件
// marshaller.marshal(person, new File("person.xml"));
} catch (JAXBException e) {
e.printStackTrace();
}实际使用中容易遇到几个典型问题:
若项目中频繁使用,可封装一个静态工具方法,隐藏重复逻辑:
public class JAXBUtil {
public static <T> String toXml(T obj) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(obj.getClass());
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
StringWriter writer = new StringWriter();
m.marshal(obj, writer);
return writer.toString();
}
}调用:String xml = JAXBUtil.toXml(new Person("李四", 30, "P002"));
注意:JDK 11+已移除JAXB内置支持,需显式添加Maven依赖:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>4.0.3</version>
</dependency>以上就是如何用Java将POJO序列化为XML JAXB Marshalling的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号