package com.common.core.utils;
|
|
import com.common.core.exception.BizException;
|
import com.google.gson.Gson;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.commons.text.StringEscapeUtils;
|
|
/**
|
* @Author: 廖振钦
|
* @description: gonsutils
|
* @date 2022-01-06:10:45
|
* */
|
@Slf4j
|
public class GsonUtils {
|
|
public static Gson g = new Gson();
|
|
|
public static <T> T fromJson(String json, Class<? extends T> t, int layer){
|
if(layer < 5) {
|
try {
|
if(layer == 0){
|
return g.fromJson(json, t);
|
}else if (layer == 1){
|
String tmp_json = StringEscapeUtils.unescapeJson(StringEscapeUtils.unescapeHtml4(json));
|
return g.fromJson(tmp_json, t);
|
}else if (layer == 2){
|
String tmp_json = StringEscapeUtils.unescapeJson(StringEscapeUtils.unescapeHtml4(json));
|
String overjson = toJsonString(tmp_json);
|
return g.fromJson(overjson, t);
|
}else if (layer == 3){
|
String overjson=json.replaceAll("\"}\",", "\"/}\",");
|
return g.fromJson(overjson, t);
|
}else{
|
String overjson = toJsonString(json);
|
return g.fromJson(overjson, t);
|
}
|
} catch (Exception e) {
|
return fromJson(json, t, layer + 1);
|
}
|
}else{
|
log.error("GSON解析异常:"+json);
|
throw new BizException("JSON解析异常");
|
}
|
}
|
|
private static String toJsonString(String s) {
|
char[] tempArr = s.toCharArray();
|
int tempLength = tempArr.length;
|
for (int i = 0; i < tempLength; i++) {
|
if (tempArr[i] == ':' && tempArr[i + 1] == '"') {
|
for (int j = i + 2; j < tempLength; j++) {
|
if (tempArr[j] == '"') {
|
if (tempArr[j + 1] != ',' && tempArr[j + 1] != '}') {
|
tempArr[j] = '”'; // 将value中的 双引号替换为中文双引号
|
} else if (tempArr[j + 1] == ',' || tempArr[j + 1] == '}') {
|
break;
|
}
|
}
|
}
|
}
|
}
|
return new String(tempArr);
|
}
|
|
public static String toJson(Object o){
|
return g.toJson(g);
|
}
|
}
|