文章目錄
- 前言
- 一、配置文件
- 二、配置類
- 三、注解
- 四、json工具類
- 1. 工具內容
- 2. 使用工具
前言
前端在給我發送請求的時候一般包含三個部分url,header,body。那么就會涉及我們后端如何接收這些請求參數并且我們處理完畢參數后前端又如何接收參數
通過url傳遞參數一般情況我們不需要序列化/反序列化處理,而通過body傳遞的參數我們就需要**反序列化**
處理。處理完畢后參數返回給前端就是**序列化**
一、配置文件
在rouyi-admin的application.yml文件中配置了如下內容
spring:jackson:# 日期格式化date-format: yyyy-MM-dd HH:mm:ssserialization:# 格式化輸出indent_output: false# 忽略無法轉換的對象fail_on_empty_beans: falsedeserialization:# 允許對象忽略json中不存在的屬性fail_on_unknown_properties: false
二、配置類
位于package com.ruoyi.framework.config添加如下配置并且交給bean管理
@Slf4j
@Configuration
public class JacksonConfig {@Beanpublic Jackson2ObjectMapperBuilderCustomizer customizer() {return builder -> {// 全局配置序列化返回 JSON 處理JavaTimeModule javaTimeModule = new JavaTimeModule();javaTimeModule.addSerializer(Long.class, BigNumberSerializer.INSTANCE);javaTimeModule.addSerializer(Long.TYPE, BigNumberSerializer.INSTANCE);javaTimeModule.addSerializer(BigInteger.class, BigNumberSerializer.INSTANCE);javaTimeModule.addSerializer(BigDecimal.class, ToStringSerializer.instance);DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(formatter));javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(formatter));builder.modules(javaTimeModule);builder.timeZone(TimeZone.getDefault());log.info("初始化 jackson 配置");};}
}
三、注解
如果配置的無法滿足需求可以通過注解的方式解決
/*** 搜索值*/
@JsonIgnore // 不進行序列化與反序列化處理
@TableField(exist = false)
private String searchValue;
/**
* 請求參數
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY) // 只要非空的時候進行序列化與反序列化處理
@TableField(exist = false)
private Map<String, Object> params = new HashMap<>();
@JsonIgnore
@JsonProperty // 指定別名
public String getPassword() {return password;
}
@JsonFormat(pattern = "yyyy-MM-dd") // 指定日期序列化與反序列化格式格式
四、json工具類
1. 工具內容
位于package com.ruoyi.common.utils;包下
/*** JSON 工具類** @author 芋道源碼*/
// 生成一個私有的無參構造函數
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtils {// 創建OBJECT_MAPPER實例對象private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);// 獲取OBJECT_MAPPER實例對象public static ObjectMapper getObjectMapper() {return OBJECT_MAPPER;}// 將對象轉換為字符串public static String toJsonString(Object object) {if (ObjectUtil.isNull(object)) {return null;}try {return OBJECT_MAPPER.writeValueAsString(object);} catch (JsonProcessingException e) {throw new RuntimeException(e);}}// 將字符串轉換為對象public static <T> T parseObject(String text, Class<T> clazz) {if (StringUtils.isEmpty(text)) {return null;}try {return OBJECT_MAPPER.readValue(text, clazz);} catch (IOException e) {throw new RuntimeException(e);}}// 將字節數組轉換為對象public static <T> T parseObject(byte[] bytes, Class<T> clazz) {if (ArrayUtil.isEmpty(bytes)) {return null;}try {return OBJECT_MAPPER.readValue(bytes, clazz);} catch (IOException e) {throw new RuntimeException(e);}}// 將字符串轉換為對象(使用TypeReference)public static <T> T parseObject(String text, TypeReference<T> typeReference) {if (StringUtils.isBlank(text)) {return null;}try {return OBJECT_MAPPER.readValue(text, typeReference);} catch (IOException e) {throw new RuntimeException(e);}}// 將字符串轉換為字典使用比hashmap更簡單public static Dict parseMap(String text) {if (StringUtils.isBlank(text)) {return null;}try {return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));} catch (MismatchedInputException e) {// 類型不匹配說明不是jsonreturn null;} catch (IOException e) {throw new RuntimeException(e);}}// 將字符串轉換為字典列表public static List<Dict> parseArrayMap(String text) {if (StringUtils.isBlank(text)) {return null;}try {return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));} catch (IOException e) {throw new RuntimeException(e);}}// 將字符串轉換為對象列表public static <T> List<T> parseArray(String text, Class<T> clazz) {if (StringUtils.isEmpty(text)) {return new ArrayList<>();}try {return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));} catch (IOException e) {throw new RuntimeException(e);}}}
2. 使用工具
測試getObjectMapper方法
@RestController
@RequestMapping("/demo/test")
@SaIgnore // 忽略校驗
public class TestController {@GetMapping("JsonUtils")public void testGetObjectMapper(){// 獲取objectMapper ObjectMapper objectMapper = JsonUtils.getObjectMapper();// 打印Console.log("objectMapper,{}",objectMapper);}
}
測試toJsonString方法,將對象轉換為字符串
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建對象User user = new User("張三" , 18);// 序列化String str = JsonUtils.toJsonString(user);Console.log(str);}
測試parseObject方法,將字符串轉換對象
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="{\"name\":\"張三\",\"age\":18}";// 反序列化User user = JsonUtils.parseObject(json, User.class);Console.log(user);}
測試parseObject方法,將字節數組轉換對象
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="{\"name\":\"張三\",\"age\":18}";// 反序列化User user = JsonUtils.parseObject(StrUtil.utf8Bytes(json), User.class);Console.log(user);}
測試parseObject方法,將字符串轉換為復雜類型
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="[{\"name\":\"張三\",\"age\":18}]";// 反序列化List<User> users = JsonUtils.parseObject(json, new TypeReference<List<User>>() {});Console.log(users);}
測試parseMap方法,將字符串轉換字典,Dict繼承了LinkedHashMap對其做了進一步增強
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="{\"name\":\"張三\",\"age\":18}";// 反序列化Dict dict = JsonUtils.parseMap(json);if (dict != null) {Console.log(dict.get("name"));}}
測試parseArrayMap方法,將字符串轉換字典列表,Dict繼承了LinkedHashMap對其做了進一步增強
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="[{\"name\":\"張三\",\"age\":18}]";// 反序列化List<Dict> dictList = JsonUtils.parseArrayMap(json);if (CollectionUtil.isNotEmpty(dictList)) {for (Dict dict : dictList) {Console.log("name: {}, age: {}", dict.getStr("name"), dict.getInt("age"));}}}
測試parseArrayMap方法,將字符串轉換字典列表
@GetMapping("JsonUtils")public void testGetObjectMapper(){// 創建jsonString json="[{\"name\":\"張三\",\"age\":18}]";// 反序列化List<User> userList = JsonUtils.parseArray(json, User.class);if (CollectionUtil.isNotEmpty(userList)) {for (User user : userList) {Console.log("name: {}, age: {}", user.getName(), user.getAge());}}}