zoukankan      html  css  js  c++  java
  • 记一次踩坑 Gson转换map对象时 Integer类型自动转换成Double类型

    之前一直使用json转换map对象,因为公司统一使用gson,我按照网上转换map对象的方式转换:

    Map<String, Object> params = gson.fromJson(gson.toJson(payMentResultDto), Map.class); 

    结果对象里Integer类型自动变成double类型。。。

    解决办法:

    网上大致有俩种,1、修改源码(能力达不到)2、增加适配器

    我找了一下,解决办法有俩种(比较实用)

    1、网上看到的(自定义类型适配器),亲测可用

     //这俩段都是定义:
    private static Type typeToken = new TypeToken<TreeMap<String, Object>>(){}.getType();
    Gson gson = new GsonBuilder()
                .registerTypeAdapter(
                        new TypeToken<TreeMap<String, Object>>(){}.getType(),
                        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();
    //实际调用
    Map<String, Object> params = gson.fromJson(gson.toJson(payMentResultDto), typeToken);
     原文链接:https://blog.csdn.net/wusj3/java/article/details/79525255

    2、把对象中的Integer类型改成String类型,这样就不会被自动转换了

  • 相关阅读:
    5_添加购物车 View+Con
    5_添加购物车 B+M
    5_添加购物车 D
    登录注册V
    bootstrap-标题
    h5整理--详解css的相对定位和绝对定位
    各大门户网站的css初始化代码
    九月二十八JS验证
    js函数和运算符
    4.1原始表达式 9/16
  • 原文地址:https://www.cnblogs.com/lxk233/p/12696025.html
Copyright © 2011-2022 走看看