测试用户
2023-04-13 43393f2bb11cbf9e6af40077bbc5284660e8a754
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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);
    }
}