目录
文章目录
- 一,Fastjson到Jackson的替换方案
-
- 方案代码
- 序列化
- 反序列化
- 通过key获取某种类型的值
- 类型替换
- 二,Springboot工程中序列化的使用场景
- 三,SpringMVC框架中的Http消息转换器
-
- 1,原理:
- 2,自定义消息转换器
-
- Fastjson序列化消息转换器定义:
- Jackson序列化消息转换器定义:
- 3,Jackson常用注解自定义序列化规则
一,Fastjson到Jackson的替换方案
方案代码
package main.java.solutions;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtil {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
OBJECT_MAPPER.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, true);
OBJECT_MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
OBJECT_MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
SimpleModule module = new SimpleModule();
module.addSerializer(BigDecimal.class, ToStringSerializer.instance);
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
module.addSerializer(LocalDate.class, new LocalDateSerializer());
module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeSerializer());
module.addDeserializer(LocalDate.class, new LocalDateDeSerializer());
OBJECT_MAPPER.registerModule(module);
}
public static ObjectMapper getObjectMapper() {
return OBJECT_MAPPER;
}
public static String toJsonOrNull(Object object) {
if (object == null) {
return null;
}
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("Json serialize error :", e);
}
return null;
}
public static String toJsonString(Object object) throws Exception {
if (object == null) {
return null;
}
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
log.error("Json serialize error :", e);
throw new Exception("Json serialize error");
}
}
public static <T> T parseObject(String json, Class<T> classType) throws Exception {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(json, classType);
} catch (Exception e) {
log.error("Json de-serialize error :", e);
throw new Exception("Json de-serialize error");
}
}
public static <T> T parseObject(String json, TypeReference<T> typeReference) throws Exception{
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return OBJECT_MAPPER.readValue(json, typeReference);
} catch (Exception e) {
log.error("Json de-serialize error :", e);
throw new Exception("Json de-serialize error");
}
}
public static Map<String, Object> parseMap(String json) throws Exception{
return parseObject(json, new TypeReference<Map<String, Object>>() {});
}
@SuppressWarnings("unchecked")
public static <T> List<T> parseArray(String json, Class<T> classType) throws Exception {
if (StringUtils.isEmpty(json)) {
return null;
}
try {
return parseCollection(json, ArrayList.class, classType);
} catch (Exception e) {
log.error("Error occurred during json deserialization for List: ", e);
throw new Exception("Error occurred during json deserialization");
}
}
public static <C extends Collection<T>, T> C parseCollection(String jsonStr, Class<C> resultClass, Class<T> classType) throws IOException {
return OBJECT_MAPPER.readValue(jsonStr, OBJECT_MAPPER.getTypeFactory().constructCollectionType(resultClass, classType));
}
public static Long getLong(Map<String, Object> map, String key) throws Exception {
return TypeUtils.castToLong(map.get(key));
}
public static Integer getInteger(Map<String, Object> map, String key) throws Exception{
return TypeUtils.castToInt(map.get(key));
}
public static String getString(Map<String, Object> map, String key) {
return TypeUtils.castToString(map.get(key));
}
}
package main.java.solutions;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TypeUtils {
private static final Pattern NUMBER_WITH_TRAILING_ZEROS_PATTERN = Pattern.compile("\\.0*$");
public static String castToString(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
public static Integer castToInt(Object value) throws Exception{
if (value == null) {
return null;
}
if (value instanceof Integer) {
return (Integer)value;
}
if (value instanceof BigDecimal) {
return intValue((BigDecimal)value);
}
if (value instanceof Number) {
return ((Number)value).intValue();
}
if (value instanceof String) {
String strVal = (String)value;
if (strVal.length() == 0
|| "null".equals(strVal)
|| "NULL".equals(strVal)) {
return null;
}
if (strVal.indexOf(',') != -1) {
strVal = strVal.replaceAll(",", "");
}
Matcher matcher = NUMBER_WITH_TRAILING_ZEROS_PATTERN.matcher(strVal);
if (matcher.find()) {
strVal = matcher.replaceAll("");
}
return Integer.parseInt(strVal);
}
if (value instanceof Boolean) {
return (Boolean)value ? 1 : 0;
}
if (value instanceof Map) {
Map map = (Map)value;
if (map.size() == 2
&& map.containsKey("andIncrement")
&& map.containsKey("andDecrement")) {
Iterator iter = map.values().iterator();
iter.next();
Object value2 = iter.next();
return castToInt(value2);
}
}
throw new Exception("Cast type error: "+value);
}
public static Long castToLong(Object value) throws Exception {
if (value == null) {
return null;
}
if (value instanceof BigDecimal) {
return longValue((BigDecimal)value);
}
if (value instanceof Number) {
return ((Number)value).longValue();
}
if (value instanceof String) {
String strVal = (String)value;
if (strVal.length() == 0
|| "null".equals(strVal)
|| "NULL".equals(strVal)) {
return null;
}
if (strVal.indexOf(',') != -1) {
strVal = strVal.replaceAll(",", "");
}
try {
return Long.parseLong(strVal);
} catch (NumberFormatException ex) {
}
}
if (value instanceof Map) {
Map map = (Map)value;
if (map.size() == 2
&& map.containsKey("andIncrement")
&& map.containsKey("andDecrement")) {
Iterator iter = map.values().iterator();
iter.next();
Object value2 = iter.next();
return castToLong(value2);
}
}
if (value instanceof Boolean) {
return (Boolean)value ? 1L : 0L;
}
throw new Exception("Cast type error: "+value);
}
public static int intValue(BigDecimal decimal) {
if (decimal == null) {
return 0;
}
int scale = decimal.scale();
if (scale >= -100 && scale <= 100) {
return decimal.intValue();
}
return decimal.intValueExact();
}
public static long longValue(BigDecimal decimal) {
if (decimal == null) {
return 0;
}
int scale = decimal.scale();
if (scale >= -100 && scale <= 100) {
return decimal.longValue();
}
return decimal.longValueExact();
}
}
序列化
1,JSON.toJSONString(this)和JSON.toJSON(this); if为null,则返回null,如果转换异常,就抛异常。
如果是日志打印就使用JsonUtils.toJsonOrNull(this)替换,否则使用JsonUtils.toJsonString(this)
反序列化
1,JSON.parseObject(deviceInfoStr, DeviceInfo.class); if为null,则返回null,如果转换异常,就抛异常
使用**JsonUtils.parseObject(deviceInfoStr, DeviceInfo.class)**替换
2,JSON.parseObject(String text);if为null,则返回null,如果转换异常,就抛异常
使用 **JsonUtils.parseMap(String json)**替换
3,JSONObject.parseArray(String text, Class clazz);if为null,则返回null,如果转换异常,就抛异常
使用 **JsonUtils.parseArray(String text, Class clazz)**替换;
通过key获取某种类型的值
1,jsonObject.getLong(String key) ;if为null,则返回null,如果转换异常,就抛异常
使用**JsonUtils.getLong(map, key)**替换;
2,jsonObject.getInteger(String key) ;if为null,则返回null,如果转换异常,就抛异常
使用 **JsonUtils.getInteger(map, key)**替换;
3,jsonObject.getString(String key) ;if为null,则返回null,如果转换异常,就抛异常
使用 **JsonUtils.getString(map, key)**替换;
类型替换
7,返回给前端的是JSONObject使用**Map**替换
8,返回给前端的是JSONArray使用**List