栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何防止gson将整数转换为双精度

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何防止gson将整数转换为双精度

1)您必须创建自定义

JsonDeserializer
而不是
JsonSerializer
您的问题。

2)我不认为这种行为来自

Double
解串器。它更像是json对象/地图问题

这是源代码:

case NUMBER:      return in.nextDouble();

因此,您可以尝试使用自定义反序列化器的方法

Map<String, Object>
(或者,如果需要,可以使用一些更通用的映射):

public static class MapDeserializerDoubleAsIntFix implements JsonDeserializer<Map<String, Object>>{    @Override  @SuppressWarnings("unchecked")    public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {        return (Map<String, Object>) read(json);    }    public Object read(JsonElement in) {        if(in.isJsonArray()){ List<Object> list = new ArrayList<Object>(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) {     list.add(read(anArr)); } return list;        }else if(in.isJsonObject()){ Map<String, Object> map = new linkedTreeMap<String, Object>(); JsonObject obj = in.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet(); for(Map.Entry<String, JsonElement> entry: entitySet){     map.put(entry.getKey(), read(entry.getValue())); } return map;        }else if( in.isJsonPrimitive()){ JsonPrimitive prim = in.getAsJsonPrimitive(); if(prim.isBoolean()){     return prim.getAsBoolean(); }else if(prim.isString()){     return prim.getAsString(); }else if(prim.isNumber()){     Number num = prim.getAsNumber();     // here you can handle double int/long values     // and return any type you want     // this solution will transform 3.0 float to long values     if(Math.ceil(num.doublevalue())  == num.longValue())        return num.longValue();     else{         return num.doublevalue();     }}        }        return null;    }}

要使用它,你必须给予适当的

TypeToken
registerTypeAdapter
gson.fromJson
功能:

String json="[{"id":1,"quantity":2,"name":"apple"}, {"id":3,"quantity":4,"name":"orange"}]";GsonBuilder gsonBuilder = new GsonBuilder();gsonBuilder.registerTypeAdapter(new TypeToken<Map <String, Object>>(){}.getType(),  new MapDeserializerDoubleAsIntFix());Gson gson = gsonBuilder.create();List<Map<String, Object>> l = gson.fromJson(json, new TypeToken<List<Map<String, Object>>>(){}.getType() );for(Map<String, Object> item : l)    System.out.println(item);String serialized = gson.toJson(l);System.out.println(serialized);

结果:

{id=1, quantity=2, name=apple}{id=3, quantity=4, name=orange}Serialized back to: [{"id":1,"quantity":2,"name":"apple"},{"id":3,"quantity":4,"name":"orange"}]

PS:这只是您可以尝试的另一种选择。我个人感觉是为您的json创建自定义对象,而不是

List<Map<String,Integer>>
更酷,更易于阅读的方式



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437116.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号