常用方法
@Slf4j
public class JsonUtils {
private static final ObjectMapper MAPPER = defaultObjectMapper(new ObjectMapper());
private JsonUtils() {
}
/**
* 将Map对象序列化为json字符串
*
* @param map
* @return
*/
public static String toJsonExcludeByteAry(Map<String, Object> map) {
try {
Map<String, Object> newMap = new HashMap<>();
for (String key : map.keySet()) {
Object val = map.get(key);
if (!(val instanceof byte[])) {
newMap.put(key, val);
}
}
return MAPPER.writeValueAsString(newMap);
} catch (JsonProcessingException e) {
// 使用spring的异常类
throw new JsonParseException(e);
}
}
/**
* 序列化:将对象序列化为json字符串
*
* @param object
* @param <T>
* @return
*/
public static <T> String toJson(T object) {
try {
return MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
// 使用spring的异常类
throw new JsonParseException(e);
}
}
/**
* 反序列化:json字符串反序列化为对象
*
* @param json
* @param tClass
* @param <T>
* @return
*/
public static <T> T fromJson(String json, Class<T> tClass) {
try {
return (T) MAPPER.readValue(json, tClass);
} catch (JsonProcessingException e) {
// 使用spring的异常类
throw new JsonParseException(e);
}
}
/**
* 反序列化:处理泛型
*
* @param jsonString
* @param typeReference
* @param <T>
* @return
*/
public static <T> T fromJson(String jsonString, TypeReference<T> typeReference) {
try {
return MAPPER.readValue(jsonString, typeReference);
} catch (JsonProcessingException e) {
// 使用spring的异常类
log.error("json:{}", jsonString, e);
throw new JsonParseException(e);
}
}
public static ObjectMapper defaultObjectMapper(ObjectMapper objectMapper) {
objectMapper.findAndRegisterModules();
// 日期序列化为数字
objectMapper.disable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
objectMapper.disable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
// 序列化不支持的类型不报错
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.disable(SerializationFeature.FAIL_ON_SELF_REFERENCES);
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 仅序列化非空字段
//objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
// 时间设置系统默认时区
objectMapper.setTimeZone(TimeZone.getDefault());
// 默认的filter
objectMapper.setFilterProvider(new SimpleFilterProvider().setDefaultFilter(SimpleBeanPropertyFilter.serializeAll()));
return objectMapper;
}
}