New file |
| | |
| | | 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);
|
| | | }
|
| | | }
|
| | |
|
| | |
|
| | | }
|