336 lines
13 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.yexuejc.base.util;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.type.MapType;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.yexuejc.base.converter.*;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TimeZone;
import java.util.logging.Logger;
/**
* json工具类基于jackson
*
* @author maxf
* @ClassName JsonUtil
* @Description
* @date 2018/9/3 15:28
*/
public class JsonUtil {
private static Logger log = Logger.getLogger(JsonUtil.class.getName());
private JsonUtil() {
}
/**
* 作为单例全局使用
*/
private static JsonMapper jsonMapper = new JsonMapper();
static {
JsonUtil.setJavaTimeModule(JsonUtil.jsonMapper);
JsonUtil.initDefaultObjectMapper(JsonUtil.jsonMapper);
}
/**
* 对时间的支持
*
* @param jsonMapper
*/
private static void setJavaTimeModule(ObjectMapper jsonMapper) {
//设置一下时区,可以和程序同步避免时区问题
jsonMapper.setTimeZone(TimeZone.getDefault());
jsonMapper.setDateFormat(DateUtil.DATE_TIME_FORMAT);
JavaTimeModule javaTime = new JavaTimeModule();
//java time 特殊处理
javaTime.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTime.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
javaTime.addSerializer(Timestamp.class, new TimestampSerializer());
javaTime.addDeserializer(LocalDate.class, new LocalDateDeserializer());
javaTime.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
javaTime.addDeserializer(Timestamp.class, new TimestampDeserializer());
jsonMapper.registerModule(javaTime);
}
/**
* 初始化ObjectMapper为默认属性
* <pre>
* 1.序列化值为空时NON_NULL舍去字段
* 2.JsonParser.Feature.ALLOW_SINGLE_QUOTES解析JSON时允许使用单引号')作为字符串的引号(true)
* 例子:{'localDateTime':'2023-05-29T15:32:03.9770447'}
* 3.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES解析JSON时允许不使用引号作为字符串的引号(true)
* 例子:{age:12};适用于基本数据类型
* 4.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESjson对应java Bean,数据字段对不齐的情况下不报错(false)
* 5.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS(false):用于指定是否将日期类型序列化为时间戳格式。如果启用该特性则日期类型将被序列化为Unix时间戳即从1970年1月1日00:00:00 GMT开始的毫秒数。如果禁用该特性则日期类型将以其原始格式进行序列化。
* 例子(false)"timestamp": "2020-07-08T02:02:55.000+00:00"
* 例子(true)"timestamp": 1594236175000
* </pre>
*
* @param jsonMapper
*/
private static void initDefaultObjectMapper(ObjectMapper jsonMapper) {
//值为空时NON_NULL舍去字段ALWAYS:保留字段
jsonMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
jsonMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
/**
* 初始化ObjectMapper的默认属性
* <pre>
* 1.序列化值为空时ALWAYS:保留字段,值为“”
* 2.JsonParser.Feature.ALLOW_SINGLE_QUOTES解析JSON时允许使用单引号')作为字符串的引号(true)
* 例子:{'localDateTime':'2023-05-29T15:32:03.9770447'}
* 3.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES解析JSON时允许不使用引号作为字符串的引号(true)
* 例子:{age:12};适用于基本数据类型
* 4.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESjson对应java Bean,数据字段对不齐的情况下不报错(false)
* 5.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS(false):用于指定是否将日期类型序列化为时间戳格式。如果启用该特性则日期类型将被序列化为Unix时间戳即从1970年1月1日00:00:00 GMT开始的毫秒数。如果禁用该特性则日期类型将以其原始格式进行序列化。
* 例子(false)"timestamp": "2020-07-08T02:02:55.000+00:00"
* 例子(true)"timestamp": 1594236175000
* 6.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT反序列化值为空时映射到java Bean 非字符串类型值为null
* </pre>
*
* @return
*/
public static ObjectMapper acceptEmptyStringAsNullObject() {
JsonMapper jsonMapper = new JsonMapper();
setJavaTimeModule(jsonMapper);
//值为空时ALWAYS:保留字段默认字符串值为“”对象值为null
jsonMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
jsonMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
jsonMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
jsonMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
jsonMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
//值为空时,序列化所有值为“”
jsonMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
return jsonMapper;
}
//TODO 待优化
public static void initSnakeCase() {
//驼峰下划线互转
jsonMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
}
/**
* 这个设置不能改变JsonUtil自带的objectMapper设置只能修改传入objMapper的设置
*
* @param objMapper
*/
public static void initSnakeCase(ObjectMapper objMapper) {
//驼峰下划线互转
objMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
}
/**
* 每调用一次生成一个全新的ObjectMapper供特殊场景使用与通用ObjectMapper没有关系
*
* @return
*/
public static ObjectMapper genObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
JsonUtil.initDefaultObjectMapper(objectMapper);
return objectMapper;
}
/**
* 返回 ObjectMapper对象供外部设置特定参数
*
* @return
*/
public static ObjectMapper getJsonMapper() {
return jsonMapper;
}
/**
* 将json转换为某个类
*
* @param json InputStream类型json数据
* @param cls 转换类class
* @return 对象实例
*/
public static <T> T json2Obj(InputStream json, Class<T> cls) {
T pojo = null;
try {
pojo = jsonMapper.readValue(json, cls);
} catch (JsonParseException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
} catch (JsonMappingException e) {
log.warning("json to Object JsonMappingException.\n" + e.getMessage());
} catch (IOException e) {
log.warning("json to Object IOException.\n" + e.getMessage());
}
return pojo;
}
/**
* 将json转换为某个类
*
* @param json String类型json数据
* @param cls 转换类class
* @return 对象实例
*/
public static <T> T json2Obj(String json, Class<T> cls) {
T pojo = null;
try {
pojo = jsonMapper.readValue(json, cls);
} catch (JsonParseException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
} catch (JsonMappingException e) {
log.warning("json to Object JsonMappingException.\n" + e.getMessage());
} catch (IOException e) {
log.warning("json to Object IOException.\n" + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return pojo;
}
/**
* Json字符串转换为Java对象
*
* @param json 字符串
* @param parametrized 容器类
* @param parameterClasses 实际类
* @return
*/
public static <T> T json2Obj(String json, Class<T> parametrized, Class<?>... parameterClasses) {
T pojo = null;
JavaType javaType = jsonMapper.getTypeFactory().constructParametricType(parametrized, parameterClasses);
try {
pojo = jsonMapper.readValue(json, javaType);
} catch (JsonParseException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
} catch (JsonMappingException e) {
log.warning("json to Object JsonMappingException.\n" + e.getMessage());
} catch (IOException e) {
log.warning("json to Object IOException.\n" + e.getMessage());
}
return pojo;
}
/**
* Json字符串转换为Java-Map对象
*
* @param json 字符串
* @param mapClass Map 继承类
* @param keyClass Key 类
* @param valueClass Value 类
* @param <T>
* @return
*/
public static <T> T json2Obj(String json, Class<? extends Map> mapClass, Class<?> keyClass, Class<?> valueClass) {
T pojo = null;
MapType mapType = jsonMapper.getTypeFactory().constructMapType(mapClass, keyClass, valueClass);
try {
pojo = jsonMapper.readValue(json, mapType);
} catch (JsonParseException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
} catch (JsonMappingException e) {
log.warning("json to Object JsonMappingException.\n" + e.getMessage());
} catch (IOException e) {
log.warning("json to Object IOException.\n" + e.getMessage());
}
return pojo;
}
/**
* Json字符串转换为Java-Map对象
*
* @param json 字符串
* @param javaType 具体的java类型
* @param <T>
* @return
*/
public static <T extends Object> T json2Obj(String json, TypeReference<T> javaType) {
try {
return jsonMapper.readValue(json, javaType);
} catch (JsonProcessingException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
}
return null;
}
/**
* Json字符串转换为Java对象
*
* @param json 字符串
* @param parametrized 容器类
* @param parameterClasses 实际类
* @return
*/
public static <T> T json2Obj(InputStream json, Class<T> parametrized, Class<?>... parameterClasses) {
T pojo = null;
JavaType javaType = jsonMapper.getTypeFactory().constructParametrizedType(parametrized, parametrized,
parameterClasses);
try {
pojo = jsonMapper.readValue(json, javaType);
} catch (JsonParseException e) {
log.warning("json to Object JsonParseException.\n" + e.getMessage());
} catch (JsonMappingException e) {
log.warning("json to Object JsonMappingException.\n" + e.getMessage());
} catch (IOException e) {
log.warning("json to Object IOException.\n" + e.getMessage());
}
return pojo;
}
/**
* 将任何对象转换为json
*
* @param pojo 要转换的对象
* @return 返回json
*/
public static String obj2Json(Object pojo) {
String json = null;
try {
json = jsonMapper.writeValueAsString(pojo);
} catch (JsonProcessingException e) {
log.warning("json to Object JsonProcessingException.\n" + e.getMessage());
}
return json;
}
/**
* 格式化输出
*
* @param obj 需要输出对象
* @return 格式化后的字符串
*/
public static String formatPrinter(Object obj) {
String json = null;
try {
json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
} catch (JsonProcessingException e) {
log.warning("json to Object JsonProcessingException.\n" + e.getMessage());
}
return json;
}
}