wjc
2023-06-28 14de918a79943e4961b09fa01ed320c6cad41f2e
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
package com.hdl.sdk.link.common.utils.gson;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
 
import java.lang.reflect.Type;
 
/**
 * Created by Tong on 2021/9/8.
 */
public class GsonConvert {
 
    private static Gson gson = null;
 
    public static Gson getGson() {
        if (gson == null) {
            synchronized (GsonConvert.class) {
                if (gson == null) {
                    gson = new GsonBuilder()
                            .setPrettyPrinting()
                            .disableHtmlEscaping()
                            .registerTypeAdapter(String.class, new StringTypeAdapter())
                            .create();
                }
            }
        }
        return gson;
    }
 
    public static <T> T copyProperties(Object o, Type type) {
        return getGson().fromJson(getGson().toJson(o), type);
    }
 
    private static class StringTypeAdapter implements JsonSerializer<String>, JsonDeserializer<String> {
        @Override
        public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            if (json instanceof JsonPrimitive) {
                return json.getAsString();
            } else {
                return json.toString();
            }
        }
 
        @Override
        public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src);
        }
    }
 
 
}