package com.ruoyi.payment.wx.utils;
|
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
import lombok.extern.slf4j.Slf4j;
|
|
/**
|
* Json转换工具类
|
*
|
* @author madman
|
*/
|
@Slf4j
|
public final class WxJsonUtils {
|
private static final ObjectMapper OM = new ObjectMapper();
|
private static final JavaTimeModule timeModule = new JavaTimeModule();
|
|
|
/**
|
* 设置 ObjectMapper
|
*
|
* @return
|
*/
|
private static ObjectMapper getObjectMapper() {
|
// 允许对象忽略json中不存在的属性
|
OM.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
OM.registerModule(timeModule);
|
return OM;
|
}
|
|
/**
|
* 将对象序列化
|
*/
|
public static <T> String toJsonString(T obj) {
|
try {
|
ObjectMapper om = getObjectMapper();
|
// 忽略空值
|
om.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
|
return om.writeValueAsString(obj);
|
} catch (JsonProcessingException e) {
|
log.error("转json字符串失败:{}", obj);
|
return null;
|
}
|
}
|
|
/**
|
* 反序列化对象字符串
|
*/
|
public static <T> T parseObject(String json, Class<T> clazz) {
|
try {
|
ObjectMapper om = getObjectMapper();
|
return om.readValue(json, clazz);
|
} catch (JsonProcessingException e) {
|
throw new RuntimeException("反序列化对象字符串失败");
|
}
|
}
|
|
/**
|
* 反序列化字符串成为对象
|
*/
|
public static <T> T parseObject(String json, TypeReference<T> valueTypeRef) {
|
try {
|
ObjectMapper om = getObjectMapper();
|
return om.readValue(json, valueTypeRef);
|
} catch (JsonProcessingException e) {
|
throw new RuntimeException("反序列化字符串成为对象失败");
|
}
|
}
|
|
}
|