gson自定义适配器



import com.changfu.common.json.*;
import com.google.gson.*;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class JsonUtil {

    private static Gson gson = new GsonBuilder().create();

    private static Gson customGson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateAdapter())
            .registerTypeAdapter(Integer.class, new IntegerDeserializer())
            .registerTypeAdapter(Long.class, new LongDeserializer())
            .registerTypeAdapter(BigDecimal.class, new BigDecimalDeserializer())
            .registerTypeAdapter(
                    TreeMap.class,
                    new JsonDeserializer<TreeMap<String, Object>>() {
                        @Override
                        public TreeMap<String, Object> deserialize(
                                JsonElement json, Type typeOfT,
                                JsonDeserializationContext context) throws JsonParseException {

                            TreeMap<String, Object> treeMap = new TreeMap<>();
                            JsonObject jsonObject = json.getAsJsonObject();
                            Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                            for (Map.Entry<String, JsonElement> entry : entrySet) {
                                Object ot = entry.getValue();
                                if (ot instanceof JsonPrimitive) {
                                    treeMap.put(entry.getKey(), ((JsonPrimitive) ot).getAsString());
                                } else {
                                    treeMap.put(entry.getKey(), ot);
                                }
                            }
                            return treeMap;
                        }
                    }).create();


    private static Gson customSerializer = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateAdapter())
            .registerTypeAdapter(Integer.class, new IntegerDeserializer())
            .registerTypeAdapter(Long.class, new LongDeserializer())
            .registerTypeAdapter(BigDecimal.class, new BigDecimalDeserializer())
            .registerTypeAdapter(BigDecimal.class, new BigDecimalSerializer())
            .registerTypeAdapter(Long.class, new LongSerializer())
            .registerTypeAdapter(Integer.class, new IntegerSerializer())
            .create();


    private static JsonParser jsonParser = new JsonParser();

    public static String encode(Object obj) {
        return gson.toJson(obj);
    }

    public static String customEncode(Object obj) {
        return customSerializer.toJson(obj);
    }


    public static <T> T decode(String json, Class<T> classOfT) {
        return gson.fromJson(json, classOfT);
    }

    public static <T> T decode(JsonElement jsonElement, Class<T> classOfT) {

        return gson.fromJson(jsonElement, classOfT);
    }

    /**
     * 自定义解析规则:
     * 1、"" 转 Integer、Long、Bigdecimal 返回null
     *
     * @param json
     * @param classOfT
     * @param <T>
     * @return
     */
    public static <T> T decodeByCustomGson(String json, Class<T> classOfT) {
        return customGson.fromJson(json, classOfT);
    }

    public static <T> T decodeByCustomGson(String json, Type type) {
        return customGson.fromJson(json, type);
    }

    public static JsonObject parseToJsonObject(String content) {
        return jsonParser.parse(content).getAsJsonObject();
    }

    public static JsonArray parseToJsonArray(String content) {
        return jsonParser.parse(content).getAsJsonArray();
    }


    public static void main(String[] args) {


    }



}



import com.google.gson.*;

import java.lang.reflect.Type;
import java.sql.Date;
import java.text.SimpleDateFormat;

/**
 * @Author:FeiCongcong
 * @Date:2017/6/21 0021 14:32
 */
public class DateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {

    @Override
    public Date deserialize(JsonElement json, Type typeOfT,
                            JsonDeserializationContext context) throws JsonParseException {
        if (json == null) {
            return null;
        } else {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return new Date(sdf.parse(json.getAsString()).getTime());
            } catch (Exception e) {
                return null;
            }
        }
    }

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc,
                                 JsonSerializationContext context) {
        String value = "";
        if (src != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            value = sdf.format(src);
        } else {
            return null;
        }
        return new JsonPrimitive(value);
    }

}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值