package com.weds.framework.core.util.common;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* @description: <br/>
* Json工具类
* <p>
* <br/>
* @author: Qz1997
* @create 2019/11/7 10:59
*/
@SuppressWarnings("unused")
@Slf4j
public final class JsonUtils {
public static final ObjectMapper MAPPER = new ObjectMapper();
/**
* 序列化 对象 序列化为 Json 字符串
*
* @param obj 对象
* @return Json 字符串
*/
@Nullable
public static String serialize(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return MAPPER.writeValueAsString(obj);
} catch (Exception e) {
log.error("json序列化出错:" + obj, e);
return null;
}
}
/**
* 解析json 简单泛型
*
* @param json json 字符串
* @param tClass 类型
* @param <T> 类型
* @return 实体
*/
@Nullable
public static <T> T parse(String json, Class<T> tClass) {
try {
return MAPPER.readValue(json, tClass);
} catch (Exception e) {
log.error("json解析出错:" + json, e);
return null;
}
}
/**
* 解析json => List
*
* @param json json字符传
* @param eClass 类型
* @param <E> List泛型
* @return List
*/
@Nullable
public static <E> List<E> parseList(String json, Class<E> eClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
log.error("json解析出错:" + json, e);
return null;
}
}
/**
* json 转 Map
*
* @param json json 字符串
* @param kClass key Class
* @param vClass value Class
* @param <K> key 泛型
* @param <V> value 泛型
* @return Map 结果
*/
@Nullable
public static <K, V> Map<K, V> parseMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return MAPPER.readValue(json, MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
log.error("json解析出错:" + json, e);
return null;
}
}
/**
* 解析json 复杂泛型
*
* @param json json 字符串
* @param type 类型
* @param <T> 复杂泛型
* @return 泛型对象
*/
@Nullable
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return MAPPER.readValue(json, type);
} catch (IOException e) {
log.error("json解析出错:" + json, e);
return null;
}
}
}
JSON工具类
最新推荐文章于 2022-09-28 18:58:05 发布