Spring使用Jackson實現(xiàn)轉換XML與Java對象
簡介
本文介紹使用Spring自帶的Jackson轉換XML與Java對象的方法。
XML與Java對象轉換的方法有很多,最好的方法是使用Spring自帶的XmlMapper,本文介紹此工具的用法。
XmlMapper類是 ObjectMapper類的子類,兩者使用方式幾乎一致。
依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> <!-- 版本由spring-boot-starter-parent指定--> </dependency>
jackson-dataformat-xml依賴了jackson-core、jackson-databind、jackson-annotations等,這些都在spring-boot-starter-web中引入了。
整個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.4.13</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.knife</groupId> <artifactId>Demo_XML_SpringBoot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>Demo_XML_SpringBoot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.3</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
工具類
package com.knife.example.common.util; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.deser.std.DateDeserializers; import com.fasterxml.jackson.databind.ser.std.DateSerializer; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer; import lombok.SneakyThrows; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class XmlUtil { private static final XmlMapper xmlMapper = createXmlMapper(); private static XmlMapper createXmlMapper() { XmlMapper xmlMapper = XmlMapper.builder() // // 忽略實體類沒有對應屬性。如果為 true 會拋出異常 // .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false) // // 忽略null // .serializationInclusion(JsonInclude.Include.NON_NULL) // // 屬性使用 駝峰首字母小寫 // .propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE) // .defaultUseWrapper(false) .build(); // 序列化時加上文件頭信息 xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); // 美化輸出結果(給XML添加縮進) xmlMapper.enable(SerializationFeature.INDENT_OUTPUT); // 把“忽略重復的模塊注冊”禁用,否則下面的注冊不生效 xmlMapper.disable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS); xmlMapper.registerModule(configTimeModule()); // 重新設置為生效,避免被其他地方覆蓋 xmlMapper.enable(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS); return xmlMapper; } private static JavaTimeModule configTimeModule() { JavaTimeModule javaTimeModule = new JavaTimeModule(); String localDateTimeFormat = "yyyy-MM-dd HH:mm:ss"; String localDateFormat = "yyyy-MM-dd"; String localTimeFormat = "HH:mm:ss"; String dateFormat = "yyyy-MM-dd HH:mm:ss"; // 序列化 javaTimeModule.addSerializer( LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(localDateTimeFormat))); javaTimeModule.addSerializer( LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(localDateFormat))); javaTimeModule.addSerializer( LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimeFormat))); javaTimeModule.addSerializer( Date.class, new DateSerializer(false, new SimpleDateFormat(dateFormat))); // 反序列化 javaTimeModule.addDeserializer( LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(localDateTimeFormat))); javaTimeModule.addDeserializer( LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDateFormat))); javaTimeModule.addDeserializer( LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimeFormat))); javaTimeModule.addDeserializer(Date.class, new DateDeserializers.DateDeserializer(){ @SneakyThrows @Override public Date deserialize(JsonParser jsonParser, DeserializationContext dc){ String text = jsonParser.getText().trim(); SimpleDateFormat sdf = new SimpleDateFormat(dateFormat); return sdf.parse(text); } }); return javaTimeModule; } public static String toXml(Object o) { String xml = null; try { xml = xmlMapper.writeValueAsString(o); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return xml; } public static <T> T toObject(String xml, Class<T> cls) { T t = null; try { t = xmlMapper.readValue(xml, cls); } catch (JsonProcessingException e) { throw new RuntimeException(e); } return t; } }
測試類
package com.knife.example.business.controller; import com.knife.example.business.bo.SchoolBO; import com.knife.example.business.bo.StudentBO; import com.knife.example.common.util.XmlUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Api(tags = "測試XML") @RestController @RequestMapping("xml") public class TestController { @ApiOperation("對象轉XML") @PostMapping("toXmlString") public String toXmlString() { SchoolBO schoolBO = new SchoolBO(); schoolBO.setSchoolId(222); schoolBO.setSchoolName("ABC中學"); schoolBO.setSchoolEmail("aa@163.com"); schoolBO.setSchoolAddress("A省B市"); List<StudentBO> studentBOList = new ArrayList<>(); StudentBO studentBO1 = new StudentBO(); studentBO1.setStudentName("Tony"); studentBO1.setCreateTime(LocalDateTime.now()); StudentBO studentBO2 = new StudentBO(); studentBO2.setStudentName("Peter"); studentBO2.setCreateTime(LocalDateTime.now().plusSeconds(2)); studentBOList.add(studentBO1); studentBOList.add(studentBO2); schoolBO.setStudentBOList(studentBOList); return XmlUtil.toXml(schoolBO); } @ApiOperation("XML轉對象") @PostMapping("toObject") public Object toObject(String xml) { return XmlUtil.toObject(xml, SchoolBO.class); } }
實體類
@JacksonXmlRootElement:指定生成xml根標簽的名字
屬性:namespace,localName
@JacksonXmlProperty:指定包裝標簽名,或者指定標簽內部屬性名
屬性:namespace,localName,isAttribute(default:false)
@JacksonXmlElementWrapper:可用于List等集合類,用來指定外圍標簽名
屬性:namespace,localName,useWrapping (default:true)
@JacksonXmlText:指定當前這個值,沒有xml標簽包裹。
屬性:namespace,localName
頂層實體類
package com.knife.example.business.bo; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import lombok.Data; import java.util.List; @Data @JacksonXmlRootElement(localName = "school") public class SchoolBO { // 可以指定XML標簽的名字。若不指定,則為字段名 @JacksonXmlProperty(localName = "SchoolName") private String schoolName; // isAttribute 設為true時,該字段做為根標簽的屬性 @JacksonXmlProperty(isAttribute = true) private Integer schoolId; private String schoolEmail; private String schoolAddress; // 指定外層的XML標簽名 @JacksonXmlElementWrapper(localName = "students") // 指定單個元素的XML標簽名 @JacksonXmlProperty(localName = "item") private List<StudentBO> studentBOList; }
子層實體類
package com.knife.example.business.bo; import lombok.Data; import java.time.LocalDateTime; @Data public class StudentBO { private String studentName; private LocalDateTime createTime; }
測試
1.對象轉XML
2.XML轉對象
使用此XML測試:
<?xml version='1.0' encoding='UTF-8'?> <school schoolId="222"> <schoolEmail>aa@163.com</schoolEmail> <schoolAddress>A省B市</schoolAddress> <SchoolName>ABC中學</SchoolName> <students> <item> <studentName>Tony</studentName> <createTime>2023-03-06 19:46:42</createTime> </item> <item> <studentName>Peter</studentName> <createTime>2023-03-06 19:46:44</createTime> </item> </students> </school>
結果:
到此這篇關于Spring使用Jackson實現(xiàn)轉換XML與Java對象的文章就介紹到這了,更多相關Spring Jackson轉換XML內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot中l(wèi)ogback日志保存到mongoDB的方法
這篇文章主要介紹了SpringBoot中l(wèi)ogback日志保存到mongoDB的方法,2017-11-11SpringBoot中使用Guava實現(xiàn)單機令牌桶限流的示例
本文主要介紹了SpringBoot中使用Guava實現(xiàn)單機令牌桶限流的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06SpringMVC @ControllerAdvice使用場景
這篇文章主要介紹了SpringMVC @ControllerAdvice使用場景,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-11-11Java中的CyclicBarrier循環(huán)柵欄深入解析
這篇文章主要介紹了Java中的CyclicBarrier循環(huán)柵欄深入解析,CycleBarrier 它就相當于是一個柵欄,所有線程在到達柵欄后都需要等待其他線程,等所有線程都到達后,再一起通過,需要的朋友可以參考下2023-12-12基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密
這篇文章主要給大家介紹了基于SpringBoot+vue實現(xiàn)前后端數(shù)據(jù)加解密,文中有詳細的示例代碼,具有一定的參考價值,感興趣的小伙伴可以自己動手試一試2023-08-08maven <repositories>標簽和<pluginRepositories>標簽的使用
這篇文章主要介紹了maven <repositories>標簽和<pluginRepositories>標簽的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07SpringBoot使用工具類實現(xiàn)獲取容器中的Bean
這篇文章主要為大家詳細介紹了SpringBoot如何使用工具類實現(xiàn)獲取容器中的Bean,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-03-03