SpringBoot整合Jackson的过程详解
作者:李菠菜
这篇文章给大家介绍了SpringBoot整合Jackson的整合过程,文中通过代码示例给给大家介绍的非常详细,并附带附工具类与使用案例,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
环境参考
- 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> <!---################## 主要关注这个 ##################--> <!--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>
因为是Springboot-web
项目,所以直接引入Springboot-web
依赖即可,Jackson
的相关依赖被包含在Springboot-web
中。
二、在springboot的配置文件中新增配置项内容如下:
# 日期格式化 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss # 设置时区 spring.jackson.time-zone=GMT+8 # 设置空如何序列化 spring.jackson.default-property-inclusion=non_null # 格式化输出 spring.jackson.serialization.indent_output=true # 忽略无法转换的对象 spring.jackson.serialization.fail_on_empty_beans=false # 允许对象忽略json中不存在的属性 spring.jackson.deserialization.fail_on_unknown_properties=false # 允许出现特殊字符和转义符 spring.jackson.parser.allow_unquoted_control_chars=true # 允许出现单引号 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 { //对象的所有字段全部列入 OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.ALWAYS); //取消默认转换timestamps形式 OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //忽略空Bean转json的错误 OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss OBJECT_MAPPER.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误 OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } static { //对象的所有字段全部列入 OBJECT_MAPPER_SNAKE_CASE.setSerializationInclusion(JsonInclude.Include.ALWAYS); //取消默认转换timestamps形式 OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); //忽略空Bean转json的错误 OBJECT_MAPPER_SNAKE_CASE.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss OBJECT_MAPPER_SNAKE_CASE.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT)); //忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误 OBJECT_MAPPER_SNAKE_CASE.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //转换为下划线 OBJECT_MAPPER_SNAKE_CASE.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); } private JsonUtil() { } /** * 对象转Json格式字符串 * * @param obj 对象 * @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; } } /** * 对象转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(); } } /** * 对象转Json格式字符串; 属性名从驼峰改为下划线形式 * * @param obj 对象 * @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; } } /** * 字符串转换为自定义对象; 属性名从下划线形式改为驼峰 * * @param str 要转换的字符串 * @param clazz 自定义对象的class对象 * @return 自定义对象 */ 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; } } /** * 字符串转换为自定义对象(List); 属性名从下划线形式改为驼峰 * * @param str 要转换的字符串 * @param typeReference 自定义对象的typeReference List 对象 * @return 自定义对象 */ 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; } } /** * 对象转Json格式字符串(格式化的Json字符串) * * @param obj 对象 * @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; } } /** * 字符串转换为自定义对象 * * @param str 要转换的字符串 * @param clazz 自定义对象的class对象 * @return 自定义对象 */ 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; } } /** * 字符串转换为自定义字段转为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; } } }
整合完毕
使用案例
创建实体类User
,用于后续测试
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对象转Json
@Test void obj2string(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(1L); List<String> infoList = new ArrayList<>(); infoList.add("有一百万"); infoList.add("发大财"); user.setInfo(infoList); String json = JacksonUtil.obj2String(user); System.out.println(json); }
输出结果:
{"username":"clllb","age":24,"info":["有一百万","发大财"],"userId":1}
Java对象转Json(驼峰转下划线)
@Test void obj2sringSnakeCase(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(11L); List<String> infoList = new ArrayList<>(); infoList.add("有一百万"); infoList.add("发大财"); user.setInfo(infoList); String json = JacksonUtil.obj2StringFieldSnakeCase(user); System.out.println(json); }
输出结果:
{"username":"clllb","age":24,"info":["有一百万","发大财"],"user_id":11}
Java对象转file对象
@Test void obj2file(){ User user = new User(); user.setUsername("clllb"); user.setAge(24); user.setUserId(1L); List<String> infoList = new ArrayList<>(); infoList.add("有一百万"); infoList.add("发大财"); user.setInfo(infoList); String fileName = "ccccc"; JacksonUtil.obj2File(fileName,user); }
输出结果为一个文件,如下图所示:
Json转Java对象(下划线转驼峰)
@Test void string2obj(){ String json = "{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百万\",\"发大财\"],\"userId\":11}"; User user = JacksonUtil.string2Obj(json, User.class); System.out.println(user); }
输出结果:
User(username=clllb, age=24, info=[有一百万, 发大财], userId=11)
Json转Java对象集合
@Test void string2objList(){ String json = "[{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百万\",\"发大财\"],\"userId\":11},\n" + "{\"username\":\"陈老老老板\",\"age\":25,\"info\":[\"有一千万\",\"发大大财\"],\"userId\":12}]"; List<User> user = JacksonUtil.string2Obj(json, new TypeReference<List<User>>(){}); user.forEach(System.out::println); }
输出结果:
User(username=clllb, age=24, info=[有一百万, 发大财], userId=11)
User(username=陈老老老板, age=25, info=[有一千万, 发大大财], userId=12)
Json转Java对象集合(下划线转驼峰)
@Test void string2objSnakeCase(){ String json = "[{\"username\":\"clllb\",\"age\":24,\"info\":[\"有一百万\",\"发大财\"],\"user_id\":11},\n" + "{\"username\":\"陈老老老板\",\"age\":25,\"info\":[\"有一千万\",\"发大大财\"],\"user_id\":12}]"; List<User> user = JacksonUtil.string2ListFieldLowerCamelCase(json, new TypeReference<List<User>>(){}); user.forEach(System.out::println); }
输出结果:
User(username=clllb, age=24, info=[有一百万, 发大财], userId=11)
User(username=陈老老老板, age=25, info=[有一千万, 发大大财], userId=12)
以上就是SpringBoot整合Jackson的过程详解的详细内容,更多关于SpringBoot整合Jackson的资料请关注脚本之家其它相关文章!