1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath />
</parent>
<groupId>com.gzz</groupId>
<artifactId>netty</artifactId>
<version>1.0</version>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.代码
在jdk8中以下代码可以不加任何额外依赖就能正常使用,可是到了jdk17中就不管用了,其实是缺少了jaxb-runtime依赖,加上就可以正常用了
package com.gzz.netty;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MarshallerTest {
public static void main(String[] args) throws Exception {
JAXBContext jc0 = JAXBContext.newInstance(A.class);
OutputStream os = new FileOutputStream("c:\\1.xml");
Marshaller m = jc0.createMarshaller();
A a = new A();
a.setId("id for a");
B b = new B();
b.setNo(60);
a.setB(b);
m.marshal(a, os);
InputStream is = new FileInputStream("c:\\1.xml");
Unmarshaller u = jc0.createUnmarshaller();
A o = (A) u.unmarshal(is);
log.info("o.getB().getNo()={}", o.getB().getNo());
}
}
@Setter
@Getter
@XmlRootElement
class A {
private String id;
private B b;
}
@Setter
@Getter
class B {
private int no;
}
网友评论