場景:將Map<String,Object>結果序列化後放入redis緩存,發現反序列化後Integer類型自動轉換成了Double類型redis
@Test public void testJsonDefault() { Map<String,Object> map=new HashMap<>(); map.put("a","aa"); map.put("b",11); String json=GsonUtil.toJson(map,false); map=GsonUtil.fromJsonDefault(json, new TypeToken<Map<String, Object>>() { }); showMap(map); }
運行結果:json
a-aa-String緩存
b-11.0-Doubleide
/** * json字符串轉bean對象 * * @param json * @param cls * @return */ public static <T> T fromJson(String json, Class<T> cls) { Gson gson = new GsonBuilder().setDateFormat(DATEFORMAT_default) .create(); return gson.fromJson(json, cls); }
public static class MapTypeAdapter extends TypeAdapter<Object> { @Override public Object read(JsonReader in) throws IOException { JsonToken token = in.peek(); switch (token) { case BEGIN_ARRAY: List<Object> list = new ArrayList<Object>(); in.beginArray(); while (in.hasNext()) { list.add(read(in)); } in.endArray(); return list; case BEGIN_OBJECT: Map<String, Object> map = new LinkedTreeMap<String, Object>(); in.beginObject(); while (in.hasNext()) { map.put(in.nextName(), read(in)); } in.endObject(); return map; case STRING: return in.nextString(); case NUMBER: /** * 改寫數字的處理邏輯,將數字值分爲整型與浮點型。 */ double dbNum = in.nextDouble(); // 數字超過long的最大值,返回浮點類型 if (dbNum > Long.MAX_VALUE) { return dbNum; } // 判斷數字是否爲整數值 long lngNum = (long) dbNum; if (dbNum == lngNum) { return lngNum; } else { return dbNum; } case BOOLEAN: return in.nextBoolean(); case NULL: in.nextNull(); return null; default: throw new IllegalStateException(); } } @Override public void write(JsonWriter out, Object value) throws IOException { // 序列化無需實現 } }
繼續測試:測試
@Test public void testfromJson() { Map<String,Object> map=new HashMap<>(); map.put("a","aa"); map.put("b",11); String json=GsonUtil.toJson(map,false); map = GsonUtil.fromJson(json, new TypeToken<Map<String, Object>>() { }); showMap(map); }
運行結果:ui
a-aa-Stringspa
b-11-Longcode