在使用Gson转map时,发现long类型数据被转换为科学计数,以下为解决方案:
1、写一个工具类 /** * Gson工具类 */ public class GsonUtils { /** * 解决gson解析long自动转为科学计数的问题 */ public static Gson getMapGson() { Gson gson = new GsonBuilder().registerTypeAdapter(Map.class, new JsonDeserializer<Map>() { public Map 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; } }).setLongSerializationPolicy(LongSerializationPolicy.STRING).create(); return gson; } }
2、调用Gson时,按照如下写法即可解决此问题;
如:
/**
* 把json字符串解析成为map
*
* @param json
* @return HashMap<String , Object>
*/
public static HashMap<String, Object> parseJsonToMap(String json) {
Gson gson = GsonUtils.getMapGson();
Type type = new TypeToken<HashMap<String, Object>>() {
}.getType();
HashMap<String, Object> map = null;
try {
map = gson.fromJson(json, type);
} catch (Exception e) {
LKLogUtil.e(e.getMessage(), e);
}
return map;
}