All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.i2soft.util.Json Maven / Gradle / Ivy

The newest version!
package com.i2soft.util;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Map;

public final class Json {
    private Json() {
    }

    public static String encode(StringMap map) {
        return new Gson().toJson(map.map());
    }

    public static String encode(Object obj) {
        return new GsonBuilder().serializeNulls().disableHtmlEscaping().create().toJson(obj);
    }

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

    public static StringMap decode(String json) {
        // CHECKSTYLE:OFF
        Type t = new TypeToken>() {
        }.getType();
        // CHECKSTYLE:ON
        Map x = getIntGson().fromJson(json, t);

        return new StringMap(x);
    }

    /**
     * 解决gson默认将int转换为double
     */
    private static Gson getIntGson() {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(new TypeToken>() {
        }.getType(), new GsonMapDeserializerFix());
        return gsonBuilder.create();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy