依赖
<!-- xml => Object --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>woodstox-core-asl</artifactId> <version>4.4.1</version> </dependency> <!-- json => Object --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.10.0</version> </dependency>
book.xml
<?xml version="1.0" encoding="UTF-8" ?> <book> <id>1</id> <name>三国演义</name> <author>罗贯中</author> </book>
book.json
{ "id": 1, "name": "三国演义", "author": "罗贯中" }
Book.java
package com.example.demo.pojo; public class Book { private Integer id; private String name; private String author; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public String toString() { return "Book{" + "id=" + id + ", name='" + name + '\'' + ", author='" + author + '\'' + '}'; } }
测试类
package com.example.demo; import com.example.demo.pojo.Book; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.JacksonXmlModule; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.junit.jupiter.api.Test; import java.io.IOException; import java.io.InputStream; public class JacksonTest { @Test public void testParseXml() throws IOException { InputStream input = JacksonTest.class.getResourceAsStream("/book.xml"); JacksonXmlModule module = new JacksonXmlModule(); XmlMapper mapper = new XmlMapper(module); Book book = mapper.readValue(input, Book.class); System.out.println(book); // Book{id=1, name='三国演义', author='罗贯中'} // 转xml String xml = mapper.writeValueAsString(book); System.out.println(xml); // <Book><id>1</id><name>三国演义</name><author>罗贯中</author></Book> } @Test public void testParseJson() throws IOException { InputStream input = JacksonTest.class.getResourceAsStream("/book.json"); ObjectMapper mapper = new ObjectMapper(); // 反序列化时忽略不存在的JavaBean属性 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Book book = mapper.readValue(input, Book.class); System.out.println(book); // Book{id=1, name='三国演义', author='罗贯中'} //JavaBean变为JSON String json = mapper.writeValueAsString(book); System.out.println(json); // {"id":1,"name":"三国演义","author":"罗贯中"} } }
参考
https://www.liaoxuefeng.com/wiki/1252599548343744/1320418596093986