package com.credithc.microenterprise.utils; import com.credithc.microenterprise.utils.adapter.DoubleDefaultAdapter; import com.credithc.microenterprise.utils.adapter.IntegerDefaultAdapter; import com.credithc.microenterprise.utils.adapter.StringDefaultAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.lang.reflect.Type; public class GsonUtil { // 禁掉html转义,否则单引号会变成\u0027,等号变成\u0036,etc. private static final Gson deserializer = new GsonBuilder().disableHtmlEscaping().create(); // Gson默认处理Date对象的序列化/反序列化是通过一个SimpleDateFormat对象来实现的,在不同环境中部署时遇到问题获取到的SimpleDateFormat的模式字符串会不一样 private static final Gson serializer = new GsonBuilder().disableHtmlEscaping().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); // 对调用主题返回参数中int,String,Double类型数据特殊处理 private static final Gson serializerTheme = new GsonBuilder() .registerTypeAdapter(Integer.class,new IntegerDefaultAdapter()) .registerTypeAdapter(String.class,new StringDefaultAdapter()) .registerTypeAdapter(Double.class,new DoubleDefaultAdapter()) .disableHtmlEscaping().create(); private GsonUtil() { } public static <T> T fromJson(String json, Class<T> clazz) { return deserializer.fromJson(json, clazz); } public static <T> T fromJson(String json, Type type) { return deserializer.fromJson(json, type); } public static <T> T fromThemeJson(String json, Type type) { return serializerTheme.fromJson(json, type); } public static <T> String toJson(T src) { return serializer.toJson(src); } /*序列化的时候附带默认值*/ public static <T> String toJsonWithDefault(T src) { return serializerTheme.toJson(src); } private static final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); public static <T> T objectFromJson(String json, Class<T> clazz) { return gson.fromJson(json, clazz); } }