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类型,这样就不会被自动转换了

  • 相关阅读:
    再谈iOS 7的手势滑动返回功能
    CGContextRef用法
    UIView的layoutSubviews和drawRect方法何时调用
    layoutSubviews何时调用的问题
    iOS应用开发最佳实践:编写高质量的Objective-C代码
    WWDC2014之App Extensions学习笔记
    定制iOS 7中的导航栏和状态栏
    从客户端中检测到有潜在危险的 Request.Form 值
    async and await 简单的入门
    C# Dictionary学习
  • 原文地址:https://www.cnblogs.com/lxk233/p/12696025.html
Copyright © 2011-2022 走看看