JAXB实例入门

[b]JAXB(Java Architecture for XML Binding)[/b],JDK标准规范,Java对象和XML之间的转换,和SAX/DOM不同的是无需关注XML解析细节。
[list]
[*]Marshalling – 把Java对象转换成XML
[*]Unmarshalling – 把XML转换成Java对象[/list]
[b]版本:[/b]
* JDK1.6开始提供JAXB 2.0(建议使用最新版JDK)
* 低于JDK1.6的版本需要下载jaxb-api.jar和jaxb-impl.jar
* JAXB还有JDK以外的很多第三方实现,比如:EclipseLink MOXy

以下代码都去掉了Bean的Setter/Getter,具体可执行的完整工程代码,可从附件下载。

[b](1) 基本[/b]

[b]Java对象 -> XML[/b]

@XmlRootElement
public class Sample {
private int id;
private String name;
private boolean flag;
}


Sample s = new Sample();
s.setId(101);
s.setName("basicObj2XML");
s.setFlag(false);

StringWriter w = new StringWriter();
// JAXB是JDK封装好的解析器
JAXB.marshal(s, new StreamResult(w)); // 输出到字符串
System.out.println(w.toString());

[quote]<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sample>
<flag>false</flag>
<id>101</id>
<name>basicObj2XML</name>
</sample>
[/quote]

转换后的XML内容可以直接输出到其他流(比如:控制台、文件等)

Sample s = new Sample();
s.setId(102);
s.setName("basicObj2Output");
s.setFlag(false);

JAXB.marshal(s, System.out); // 输出到控制台
JAXB.marshal(s, new File("d:\\jaxb_sample.xml")); // 输出到文件


[b]XML -> Java对象[/b]

String xml = "<?xml version=\"1.0\"?>"
+ "<sample>"
+ " <id>103</id>"
+ " <name>basicXML2Obj</name>"
+ " <flag>false</flag>"
+ "</sample>";

StringReader r = new StringReader(xml);
Sample ss = JAXB.unmarshal(r, Sample.class);
System.out.println(ss.toString());


[b](2) 通过JAXBContext创建解析器[/b]

[b]创建Marshaller[/b]

JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(s, System.out);


[b]创建Unmarshaller[/b]

JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader r = new StringReader(xml);
Sample sample = unmarshaller.unmarshal(new StreamSource(r), Sample.class).getValue();
System.out.println(sample.toString());


[b]设置Marshaller属性[/b]
[b]marshaller.setProperty();[/b]

JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
Marshaller marshaller = jaxbContext.createMarshaller();
// 设置格式化后输出
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// 设置字符集
marshaller.setProperty(Marshaller.JAXB_ENCODING, Charset.defaultCharset().name());
marshaller.marshal(s, System.out);


[b](3) 采用EclipseLink MOXy作为JAXB provider[/b]
1)下载导入eclipselink.jar
2)在POJO的包下新建jaxb.properties
[quote]#Sun JAXB
javax.xml.bind.context.factory=com.sun.xml.internal.bind.v2.ContextFactory
#Eclipse MOXy
#javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory [/quote]
*** SUN的JAXB实现会在xml中添加属性standalone="yes",而EclipseLink MOXy就不会。

[b](4) 监听器[/b]

[b]marshaller.setListener();[/b]

[b]Marshaller监听器[/b]

public class MarshallListener extends Marshaller.Listener {

public void beforeMarshal(Object source) {
System.out.println("BEFORE_MARSHAL fired");
}

public void afterMarshal(Object source) {
System.out.println("AFTER_MARSHAL fired");
}

}


JAXBContext jaxbContext = JAXBContext.newInstance(Sample.class);
Marshaller marshaller = jaxbContext.createMarshaller(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring Boot中整合JAXB,您可以按照以下步骤进行操作: 1. 添加依赖:在您的项目的pom.xml文件中,添加JAXB依赖项。 ```xml <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> ``` 2. 创建Java类:创建要映射到XML的Java类。使用JAXB注解配置类和字段。 ```java @XmlRootElement public class Person { private String name; private int age; // 省略构造函数、getter和setter方法 } ``` 3. 创建XML转换工具类:创建一个工具类,用于执行XML转换操作。 ```java import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; public class JAXBUtils { public static void marshal(Object object, File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(object, file); } public static <T> T unmarshal(Class<T> clazz, File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); return clazz.cast(unmarshaller.unmarshal(file)); } } ``` 4. 配置Spring Boot:在您的Spring Boot应用程序的配置类上添加JAXB相关的配置。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.xml.MarshallingHttpMessageConverter; import org.springframework.oxm.jaxb.Jaxb2Marshaller; @Configuration public class JAXBConfig { @Bean public Jaxb2Marshaller jaxb2Marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setPackagesToScan("com.example.demo"); // 设置要扫描的包路径 return marshaller; } @Bean public HttpMessageConverter<Object> marshallingHttpMessageConverter(Jaxb2Marshaller jaxb2Marshaller) { return new MarshallingHttpMessageConverter(jaxb2Marshaller); } } ``` 5. 使用JAXB:在您的控制器或服务类中使用JAXB进行XML转换操作。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonController { @Autowired private Jaxb2Marshaller jaxb2Marshaller; @GetMapping("/person") public Person getPerson() { Person person = new Person(); person.setName("John"); person.setAge(25); return person; } @GetMapping("/xml") public String getXml() { Person person = getPerson(); StringWriter writer = new StringWriter(); jaxb2Marshaller.marshal(person, new StreamResult(writer)); return writer.toString(); } } ``` 这样,当访问`/person`接口时,将返回一个Person对象的JSON表示。当访问`/xml`接口时,将返回Person对象的XML表示。 这就是在Spring Boot中整合JAXB的基本步骤。您可以根据需要进行扩展和自定义。希望对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值