JSON工具类(FastJson,Gson,Jackson)
Posted 哲思小辉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSON工具类(FastJson,Gson,Jackson)相关的知识,希望对你有一定的参考价值。
一:FastJson工具类:
FastJsonUtil代码如下:
import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author 哲思小辉
* @version 1.0.0
* @ClassName FastJsonUtil.java
* @Description fastJson工具类
* @Param
* @createTime 2020年06月25日 16:58:00
*/
public class FastJsonUtil {
private FastJsonUtil() {
}
/**
* 转成json 字符串 (不保留格式,换行、空格都会去掉)
*
* @param object
* @return
*/
public static String toJson(Object object) {
if (object == null) {
return null;
}
if (object instanceof String) {
return String.valueOf(JSON.parse(object.toString()));
}
return JSON.toJSONString(object);
}
/**
* 转成json 字符串(保留格式)
*
* @param object
* @return
*/
public static String toJsonString(Object object) {
if (object == null) {
return null;
}
return String.valueOf(JSON.parse(JSON.toJSONString(object)));
}
/**
* 转成Map<String,Object>
*
* @param object
* @return
*/
public static Map<String, Object> toMap(Object object) {
String text = toJson(object);
Map<String, Object> map = null;
if (text != null) {
map = JSON.parseObject(text, Map.class);
}
return map;
}
/**
* 转成Map<String,String>
*
* @param object
* @return
*/
public static Map<String, String> toMapString(Object object) {
String text = toJson(object);
Map<String, String> map = null;
if (text != null) {
map = JSON.parseObject(text, new TypeReference<Map<String, String>>() {
});
}
return map;
}
/**
* 转成Map<String,T>
*
* @param object
* @return
*/
public static <T> Map<String, T> toMap(Object object, Class<T> clzz) {
String text = toJson(object);
Map<String, T> map = null;
if (text != null) {
map = JSON.parseObject(text, new ParameterizedTypeMap(clzz));
}
return map;
}
/**
* 转成List <String>
*
* @param object
* @return
*/
public static List toList(Object object) {
String text = toJson(object);
List list = null;
if (text != null) {
list = JSON.parseObject(text, List.class);
}
return list;
}
/**
* 转成List<T>
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> List<T> toList(Object object, Class<T> clzz) {
String text = toJson(object);
return JSON.parseArray(text, clzz);
}
/**
* 转成JavaBean
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> T toJavaBean(Object object, Class<T> clzz) {
String text = toJson(object);
T t = null;
if (text != null) {
t = JSON.parseObject(text, clzz);
}
return t;
}
/**
* 转成Set
*
* @param object
* @return
*/
public static Set toSet(Object object) {
String text = toJson(object);
Set set = null;
if (text != null) {
set = JSON.parseObject(text, Set.class);
}
return set;
}
/**
* 转成Set<T>
*
* @param object
* @return
*/
public static <T> Set<T> toSet(Object object, Class<T> clzz) {
String text = toJson(object);
Set<T> set = null;
if (text != null) {
set = JSON.parseObject(text, new ParameterizedTypeSet(clzz));
}
return set;
}
private static class ParameterizedTypeSet implements ParameterizedType {
Class clazz;
public ParameterizedTypeSet(Class clz) {
clazz = clz;
}
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getRawType() {
return Set.class;
}
public Type getOwnerType() {
return null;
}
}
private static class ParameterizedTypeMap implements ParameterizedType {
Class clazz;
public ParameterizedTypeMap(Class clz) {
clazz = clz;
}
public Type[] getActualTypeArguments() {
return new Type[]{String.class, clazz};
}
public Type getRawType() {
return Map.class;
}
public Type getOwnerType() {
return null;
}
}
}
二:GsonJson工具类:
GsonJsonUtil代码:
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author 哲思小辉
* @version 1.0.0
* @ClassName GsonJsonUtil.java
* @Description Gson格式化工具
* @Param
* @createTime 2020年05月13日 16:40:00
*/
public class GsonJsonUtil {
private GsonJsonUtil() {
}
private static final Gson gson = new GsonBuilder()
.enableComplexMapKeySerialization() //当Map的key为复杂对象时,需要开启该方法
.serializeNulls() //当字段值为空或null时,依然对该字段进行转换
.setDateFormat("yyyy-MM-dd HH:mm:ss:SSS") //时间转化为特定格式
.disablehtmlEscaping() //防止特殊字符出现乱码
.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> {
if (src == src.longValue()) {
return new JsonPrimitive(src.longValue());
}
return new JsonPrimitive(src);
}).create();
/**
* 转成json 字符串 如果是字符串就直接返回原字符串
*
* @param object
* @return
*/
public static String toJson(Object object) {
String jsonStr = null;
try {
if (object instanceof String) {
return (String) object;
}
jsonStr = gson.toJson(object);
} catch (Exception e) {
log.error("json数据格式化报异常{}", e);
}
return jsonStr;
}
/**
* 转成Map<String,T>
*
* @param object
* @return
*/
public static <T> Map<String, T> toMap(Object object, Class<T> clzz) {
String text = toJson(object);
Map<String, T> map = null;
if (text != null) {
try {
map = gson.fromJson(text, new ParameterizedTypeMap(clzz));
} catch (Exception e) {
log.error("json字符串转Map<String, T>异常:{}", e);
}
}
return map;
}
/**
* 转成Map<String,JsonObject>
*
* @param object
* @return
*/
public static Map<String, JsonObject> toMap(Object object) {
String text = toJson(object);
Map<String, JsonObject> map = null;
if (text != null) {
try {
map = gson.fromJson(text, new TypeToken<Map<String, JsonObject>>() {
}.getType());
} catch (Exception e) {
log.error("json字符串转Map<String, JsonObject>异常:{}", e);
}
}
return map;
}
/**
* 转成List 里面默认数据类型是LinkedTreeMap所以直接转成JsonObject类型
*
* @param object
* @return
*/
public static List<JsonObject> toList(Object object) {
String text = toJson(object);
List<JsonObject> list = null;
if (text != null) {
try {
list = gson.fromJson(text, new TypeToken<List<JsonObject>>() {
}.getType());
} catch (Exception e) {
log.error("json字符串转List<JsonObject>异常:{}", e);
}
}
return list;
}
/**
* 转成List<T>
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> List<T> toList(Object object, Class<T> clzz) {
String text = toJson(object);
List<T> list = null;
if (text != null) {
try {
list = gson.fromJson(text, new ParameterizedTypeList(clzz));
} catch (Exception e) {
log.error("json字符串转List<T>异常:{}", e);
}
}
return list;
}
/**
* 转成JavaBean
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> T toJavaBean(Object object, Class<T> clzz) {
String text = toJson(object);
T t = null;
if (text != null && clzz != null) {
try {
t = gson.fromJson(text, clzz);
} catch (Exception e) {
log.error("json字符串转T异常:{}", e);
}
}
return t;
}
/**
* 转成Set<JsonObject>
*
* @param object
* @return
*/
public static Set<JsonObject> toSet(Object object) {
String text = toJson(object);
Set<JsonObject> set = null;
if (text != null) {
try {
set = gson.fromJson(text, new TypeToken<Set<JsonObject>>() {
}.getType());
} catch (Exception e) {
log.error("json字符串转Set<JsonObject>异常:{}", e);
}
}
return set;
}
/**
* 转成Set<T>
*
* @param object
* @param clzz
* @return
*/
public static <T> Set<T> toSet(Object object, Class<T> clzz) {
String text = toJson(object);
Set<T> set = null;
if (text != null) {
try {
set = gson.fromJson(text, new ParameterizedTypeSet(clzz));
} catch (Exception e) {
log.error("json字符串转Set<T>异常:{}", e);
}
}
return set;
}
private static class ParameterizedTypeList implements ParameterizedType {
Class clazz;
public ParameterizedTypeList(Class clz) {
clazz = clz;
}
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getRawType() {
return List.class;
}
public Type getOwnerType() {
return null;
}
}
private static class ParameterizedTypeSet implements ParameterizedType {
Class clazz;
public ParameterizedTypeSet(Class clz) {
clazz = clz;
}
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getRawType() {
return Set.class;
}
public Type getOwnerType() {
return null;
}
}
private static class ParameterizedTypeMap implements ParameterizedType {
Class clazz;
public ParameterizedTypeMap(Class clz) {
clazz = clz;
}
public Type[] getActualTypeArguments() {
return new Type[]{String.class, clazz};
}
public Type getRawType() {
return Map.class;
}
public Type getOwnerType() {
return null;
}
}
}
三、Jackson工具类:
JackSonJsonUtil代码如下:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author 哲思小辉
* @version 1.0.0
* @ClassName JackSonJsonUtil.java
* @Description Json工具类
* @Param
* @createTime 2020年03月25日 16:58:00
*/
public class JackSonJsonUtil {
private JackSonJsonUtil() {
}
private static final ObjectMapper objectMapper = new ObjectMapper();
static{
//序列化的时候序列对象的所有属性
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 对于空的对象转json的时候不抛出错误
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// 禁用遇到未知属性抛出异常
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT);
objectMapper.enable(JsonParser.Feature.ALLOW_COMMENTS);
objectMapper.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
objectMapper.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
}
/**
* 转成json 字符串 (不保留格式,换行、空格都会去掉)
*
* @param object
* @return
*/
public static String toJson(Object object) {
String jsonStr = null;
try {
// 针对的是转义字符串
if (object instanceof String) {
JsonNode jsonNode = objectMapper.readTree(String.valueOf(object));
jsonStr = objectMapper.writeValueAsString(jsonNode);
} else {
jsonStr = objectMapper.writeValueAsString(object);
}
} catch (JsonProcessingException e) {
log.error("json数据格式化报异常{}", e);
}
return jsonStr;
}
/**
* 转成Map<String,Object>
*
* @param object
* @return
*/
public static Map<String, Object> toMap(Object object) {
String text = toJson(object);
Map<String, Object> map = null;
if (text != null) {
try {
map = objectMapper.readValue(text, Map.class);
} catch (JsonProcessingException e) {
log.error("json字符串转Map异常:{}", e);
}
}
return map;
}
/**
* 转成Map<String,T>
*
* @param object
* @return
*/
public static <T> Map<String, T> toMap(Object object, Class<T> clzz) {
String text = toJson(object);
Map<String, T> map = null;
if (text != null && clzz != null) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructMapType(Map.class, String.class, clzz);
map = objectMapper.readValue(text, javaType);
} catch (JsonProcessingException e) {
log.error("json字符串转Map异常:{}", e);
}
}
return map;
}
/**
* 转成List <String>
*
* @param object
* @return
*/
public static List toList(Object object) {
String text = toJson(object);
List list = null;
if (text != null ) {
try {
list = objectMapper.readValue(text, List.class);
} catch (JsonProcessingException e) {
log.error("json字符串转List异常:{}", e);
}
}
return list;
}
/**
* 转成List<T>
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> List<T> toList(Object object, Class<T> clzz) {
String text = toJson(object);
List<T> list = null;
if (text != null) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, clzz);
list = objectMapper.readValue(text, javaType);
} catch (JsonProcessingException e) {
log.error("json字符串转List<T>异常:{}", e);
}
}
return list;
}
/**
* 转成JavaBean
*
* @param object
* @param clzz
* @param <T>
* @return
*/
public static <T> T toJavaBean(Object object, Class<T> clzz) {
String text = toJson(object);
T t = null;
if (text != null) {
try {
t = objectMapper.readValue(text, clzz);
} catch (JsonProcessingException e) {
log.error("json字符串转Java实体异常:{}", e);
}
}
return t;
}
/**
* 转成Set
*
* @param object
* @return
*/
public static Set toSet(Object object) {
String text = toJson(object);
Set set = null;
if (text != null) {
try {
set = objectMapper.readValue(text, Set.class);
} catch (JsonProcessingException e) {
log.error("json字符串转Set异常:{}", e);
}
}
return set;
}
/**
* 转成Set<T>
*
* @param object
* @param clzz
* @return
*/
public static <T> Set<T> toSet(Object object, Class<T> clzz) {
String text = toJson(object);
Set<T> set = null;
if (text != null) {
try {
JavaType javaType = objectMapper.getTypeFactory().constructCollectionLikeType(Set.class, clzz);
set = objectMapper.readValue(text, javaType);
} catch (JsonProcessingException e) {
log.error("json字符串转Set<T>异常:{}", e);
}
}
return set;
}
}
努力,学习,坚持
以上是关于JSON工具类(FastJson,Gson,Jackson)的主要内容,如果未能解决你的问题,请参考以下文章
Gson、FastJson、Jackson、json-lib对比总结
一文吃透Json解析工具类合集(FastJsonJacksonGson)