美文网首页
Gson转Map时,Int会变成double解决方法

Gson转Map时,Int会变成double解决方法

作者: lianpeixin | 来源:发表于2018-12-28 17:28 被阅读0次
package com.cdy.demo;

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

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.JsonObject;
import com.google.gson.JsonParseException;

public class GsonDoubleInteger {

    public static Gson getGson() {
        Gson gson = new GsonBuilder().registerTypeAdapter(HashMap.class, new JsonDeserializer<HashMap>() {
            @Override
            public HashMap<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
                HashMap<String, Object> resultMap = new HashMap<>();
                JsonObject jsonObject = json.getAsJsonObject();
                Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    resultMap.put(entry.getKey(), entry.getValue());
                }
                return resultMap;
            }
            
        }).create();
        return gson;
    }
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String aaa = "{ a: 1, b: 2.3 }";
        HashMap<String, Object> map = getGson().fromJson(aaa, HashMap.class);
        System.out.println(map);
    }
}

相关文章

网友评论

      本文标题:Gson转Map时,Int会变成double解决方法

      本文链接:https://www.haomeiwen.com/subject/fzjelqtx.html