SpringBoot整合Jackson的過(guò)程詳解
環(huán)境參考
- Jdk: 1.8
- Springboot: 2.7.6
- Jackson: 2.13.4
整合步驟
一、引入 Maven 依賴
<?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> <groupId>com.liboshuai</groupId> <artifactId>springboot-example</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-example</name> <description>springboot-example</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!--spring boot版本--> <spring-boot.version>2.7.6</spring-boot.version> <!--maven-compiler-plugin--> <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version> </properties> <dependencies> <!---################## 主要關(guān)注這個(gè) ##################--> <!--spring boot web依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--spring boot test依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <finalName>${project.artifactId}-${project.version}</finalName> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>application-${profilesActive}.properties</include> <include>application.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <configuration> <mainClass>com.liboshuai.springbootexample.SpringbootExampleApplication</mainClass> <layout>ZIP</layout> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <!-- 指定jdk版本,和指定編碼 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
因?yàn)槭?code>Springboot-web項(xiàng)目,所以直接引入Springboot-web
依賴即可,Jackson
的相關(guān)依賴被包含在Springboot-web
中。
二、在springboot的配置文件中新增配置項(xiàng)內(nèi)容如下:
# 日期格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss # 設(shè)置時(shí)區(qū) spring.jackson.time-zone=GMT+8 # 設(shè)置空如何序列化 spring.jackson.default-property-inclusion=non_null # 格式化輸出 spring.jackson.serialization.indent_output=true # 忽略無(wú)法轉(zhuǎn)換的對(duì)象 spring.jackson.serialization.fail_on_empty_beans=false # 允許對(duì)象忽略json中不存在的屬性 spring.jackson.deserialization.fail_on_unknown_properties=false # 允許出現(xiàn)特殊字符和轉(zhuǎn)義符 spring.jackson.parser.allow_unquoted_control_chars=true # 允許出現(xiàn)單引號(hào) spring.jackson.parser.allow_single_quotes=true
三、新增工具類JsonUtil
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.*; import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.List; /** * @Author liboshuai * @Date 2023/12/18 18:03 */ @Slf4j public class JsonUtil { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final ObjectMapper OBJECT_MAPPER_SNAKE_CASE = new ObjectMapper(); // 日期格式化 private static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss"; static { //對(duì)象的所有字段全部列入 OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS); //取消默認(rèn)轉(zhuǎn)換timestamps形式 OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //忽略空Bean轉(zhuǎn)json的錯(cuò)誤 OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //所有的日期格式都統(tǒng)一為以下的樣式,即yyyy-MM-dd HH:mm:ss OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); //忽略 在json字符串中存在,但是在java對(duì)象中不存在對(duì)應(yīng)屬性的情況。防止錯(cuò)誤 OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } static { //對(duì)象的所有字段全部列入 OBJECT_MAPPER_SNAKE_CASE.setSerializationInclusion(JsonInclude.Include.ALWAYS); //取消默認(rèn)轉(zhuǎn)換timestamps形式 OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //忽略空Bean轉(zhuǎn)json的錯(cuò)誤 OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //所有的日期格式都統(tǒng)一為以下的樣式,即yyyy-MM-dd HH:mm:ss OBJECT_MAPPER_SNAKE_CASE.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); //忽略 在json字符串中存在,但是在java對(duì)象中不存在對(duì)應(yīng)屬性的情況。防止錯(cuò)誤 OBJECT_MAPPER_SNAKE_CASE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //轉(zhuǎn)換為下劃線 OBJECT_MAPPER_SNAKE_CASE.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); } private JsonUtil() { } /** * 對(duì)象轉(zhuǎn)Json格式字符串 * * @param obj 對(duì)象 * @return Json格式字符串 */ public static <T> String obj2String(T obj) { if (obj == null) { return null; } try { return obj instanceof String ? (String) obj : OBJECT_MAPPER.writeValueAsString(obj); } catch (JsonProcessingException e) { log.warn("Parse Object to String error : {}", e.getMessage()); return null; } } /** * 對(duì)象轉(zhuǎn)file * @param fileName * @param obj */ public static void obj2File(String fileName,Object obj){ if (obj == null){ return; } try { OBJECT_MAPPER.writeValue(new File(fileName),obj); } catch (IOException e) { e.printStackTrace(); } } /** * 對(duì)象轉(zhuǎn)Json格式字符串; 屬性名從駝峰改為下劃線形式 * * @param obj 對(duì)象 * @return Json格式字符串 */ public static <T> String obj2StringFieldSnakeCase(T obj) { if (obj == null) { return null; } try { ObjectMapper objectMapper = OBJECT_MAPPER_SNAKE_CASE; return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj); } catch (JsonProcessingException e) { log.warn("Parse Object to String error : {}", e.getMessage()); return null; } } /** * 字符串轉(zhuǎn)換為自定義對(duì)象; 屬性名從下劃線形式改為駝峰 * * @param str 要轉(zhuǎn)換的字符串 * @param clazz 自定義對(duì)象的class對(duì)象 * @return 自定義對(duì)象 */ public static <T> T string2ObjFieldLowerCamelCase(String str, Class<T> clazz) { if (StringUtils.isEmpty(str) || clazz == null) { return null; } try { ObjectMapper objectMapper = OBJECT_MAPPER_SNAKE_CASE; return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz); } catch (Exception e) { log.warn("Parse String to Object error : {}", e.getMessage()); return null; } } /** * 字符串轉(zhuǎn)換為自定義對(duì)象(List); 屬性名從下劃線形式改為駝峰 * * @param str 要轉(zhuǎn)換的字符串 * @param typeReference 自定義對(duì)象的typeReference List 對(duì)象 * @return 自定義對(duì)象 */ public static <T> List<T> string2ListFieldLowerCamelCase(String str, TypeReference<List<T>> typeReference) { if (StringUtils.isEmpty(str) || typeReference == null) { return null; } try { ObjectMapper objectMapper = OBJECT_MAPPER_SNAKE_CASE; return objectMapper.readValue(str, typeReference); } catch (Exception e) { log.warn("Parse String to Object error : {}", e.getMessage()); return null; } } /** * 對(duì)象轉(zhuǎn)Json格式字符串(格式化的Json字符串) * * @param obj 對(duì)象 * @return 美化的Json格式字符串 */ public static <T> String obj2StringPretty(T obj) { if (obj == null) { return null; } try { return obj instanceof String ? (String) obj : OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { log.warn("Parse Object to String error : {}", e.getMessage()); return null; } } /** * 字符串轉(zhuǎn)換為自定義對(duì)象 * * @param str 要轉(zhuǎn)換的字符串 * @param clazz 自定義對(duì)象的class對(duì)象 * @return 自定義對(duì)象 */ public static <T> T string2Obj(String str, Class<T> clazz) { if (StringUtils.isEmpty(str) || clazz == null) { return null; } try { return clazz.equals(String.class) ? (T) str : OBJECT_MAPPER.readValue(str, clazz); } catch (Exception e) { log.warn("Parse String to Object error : {}", e.getMessage()); return null; } } /** * 字符串轉(zhuǎn)換為自定義字段轉(zhuǎn)為list * @param str * @param typeReference * @param <T> * @return */ public static <T> T string2Obj(String str, TypeReference<T> typeReference) { if (StringUtils.isEmpty(str) || typeReference == null) { return null; } try { return (T) (typeReference.getType().equals(String.class) ? str : OBJECT_MAPPER.readValue(str, typeReference)); } catch (IOException e) { log.warn("Parse String to Object error", e); return null; } } public static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzes) { JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(collectionClazz, elementClazzes); try { return OBJECT_MAPPER.readValue(str, javaType); } catch (IOException e) { log.warn("Parse String to Object error : {}" + e.getMessage()); return null; } } }
整合完畢
使用案例
創(chuàng)建實(shí)體類User
,用于后續(xù)測(cè)試
import lombok.Data; import java.util.List; @Data public class User { private String username; private Integer age; private List<String> info; private Long userId; }
Java對(duì)象轉(zhuǎn)Json
@Test void obj2string(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(1L); List<String> infoList = new ArrayList<>(); infoList.add("有一百萬(wàn)"); infoList.add("發(fā)大財(cái)"); user.setInfo(infoList); String json = JacksonUtil.obj2String(user); System.out.println(json); }
輸出結(jié)果:
{"username":"clllb","age":24,"info":["有一百萬(wàn)","發(fā)大財(cái)"],"userId":1}
Java對(duì)象轉(zhuǎn)Json(駝峰轉(zhuǎn)下劃線)
@Test void obj2sringSnakeCase(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(11L); List<String> infoList = new ArrayList<>(); infoList.add("有一百萬(wàn)"); infoList.add("發(fā)大財(cái)"); user.setInfo(infoList); String json = JacksonUtil.obj2StringFieldSnakeCase(user); System.out.println(json); }
輸出結(jié)果:
{"username":"clllb","age":24,"info":["有一百萬(wàn)","發(fā)大財(cái)"],"user_id":11}
Java對(duì)象轉(zhuǎn)file對(duì)象
@Test void obj2file(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(1L); List<String> infoList = new ArrayList<>(); infoList.add("有一百萬(wàn)"); infoList.add("發(fā)大財(cái)"); user.setInfo(infoList); String fileName = "ccccc"; JacksonUtil.obj2File(fileName,user); }
輸出結(jié)果為一個(gè)文件,如下圖所示:
Json轉(zhuǎn)Java對(duì)象(下劃線轉(zhuǎn)駝峰)
@Test void string2obj(){ String json = "{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百萬(wàn)\",\"發(fā)大財(cái)\"],\"userId\":11}"; User user = JacksonUtil.string2Obj(json, User.class); System.out.println(user); }
輸出結(jié)果:
User(username=clllb, age=24, info=[有一百萬(wàn), 發(fā)大財(cái)], userId=11)
Json轉(zhuǎn)Java對(duì)象集合
@Test void string2objList(){ String json = "[{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百萬(wàn)\",\"發(fā)大財(cái)\"],\"userId\":11},\n" + "{\"username\":\"陳老老老板\",\"age\":25,\"info\":[\"有一千萬(wàn)\",\"發(fā)大大財(cái)\"],\"userId\":12}]"; List<User> user = JacksonUtil.string2Obj(json, new TypeReference<List<User>>(){}); user.forEach(System.out::println); }
輸出結(jié)果:
User(username=clllb, age=24, info=[有一百萬(wàn), 發(fā)大財(cái)], userId=11)
User(username=陳老老老板, age=25, info=[有一千萬(wàn), 發(fā)大大財(cái)], userId=12)
Json轉(zhuǎn)Java對(duì)象集合(下劃線轉(zhuǎn)駝峰)
@Test void string2objSnakeCase(){ String json = "[{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百萬(wàn)\",\"發(fā)大財(cái)\"],\"user_id\":11},\n" + "{\"username\":\"陳老老老板\",\"age\":25,\"info\":[\"有一千萬(wàn)\",\"發(fā)大大財(cái)\"],\"user_id\":12}]"; List<User> user = JacksonUtil.string2ListFieldLowerCamelCase(json, new TypeReference<List<User>>(){}); user.forEach(System.out::println); }
輸出結(jié)果:
User(username=clllb, age=24, info=[有一百萬(wàn), 發(fā)大財(cái)], userId=11)
User(username=陳老老老板, age=25, info=[有一千萬(wàn), 發(fā)大大財(cái)], userId=12)
以上就是SpringBoot整合Jackson的過(guò)程詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot整合Jackson的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
java實(shí)現(xiàn)識(shí)別二維碼圖片功能方法詳解與實(shí)例源碼
這篇文章主要介紹了java實(shí)現(xiàn)識(shí)別二維碼圖片,java無(wú)法識(shí)別二維碼情況下對(duì)二維碼圖片調(diào)優(yōu)功能方法與實(shí)例源碼,需要的朋友可以參考下2022-12-12Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解
這篇文章主要介紹了Java中的List接口實(shí)現(xiàn)類LinkList和ArrayList詳解,List接口繼承自Collection接口,是單列集合的一個(gè)重要分支,實(shí)現(xiàn)了List接口的對(duì)象稱為L(zhǎng)ist集合,在List集合中允許出現(xiàn)重復(fù)的元素,所有的元素是以一種線性方式進(jìn)行存儲(chǔ)的,需要的朋友可以參考下2024-01-01SpringBoot集成POI導(dǎo)出Execl表格之統(tǒng)一工具類
這篇文章主要為大家詳細(xì)介紹了SpringBoot集成POI導(dǎo)出Execl表格之統(tǒng)一工具類,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09字節(jié)碼調(diào)教入口JVM?寄生插件javaagent
這篇文章主要介紹了字節(jié)碼調(diào)教入口JVM?寄生插件javaagent方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08SpringBoot多租戶配置與實(shí)現(xiàn)示例
本文詳細(xì)介紹了在SpringBoot中實(shí)現(xiàn)多租戶架構(gòu)的方法和步驟,包括配置數(shù)據(jù)源、Hibernate攔截器、租戶解析器等,以共享數(shù)據(jù)庫(kù)、共享數(shù)據(jù)表的方式,確保數(shù)據(jù)隔離和安全性,感興趣的可以了解一下2024-09-09