基本写法,输出数据数据都被转换成double:
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
return gson.fromJson(psiFile.getText(), TestDataModel.class);
解决方案:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Map.class, new JsonDeserializer<Map>() {
@Override
public Map deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
LinkedTreeMap<String,Object> m = new LinkedTreeMap<String, Object>();
JsonObject jo = json.getAsJsonObject();
for (Map.Entry<String, JsonElement> mx : jo.entrySet()){
String key = mx.getKey();
JsonElement v = mx.getValue();
if(v.isJsonArray()){
m.put(key, context.deserialize(v, List.class));
}else if(v.isJsonPrimitive()){
Object value = v.getAsString();
try {
Object numValue = NumberFormat.getInstance().parse((String)value);
if (numValue != null && numValue.toString().equals(value)) {
value = numValue;
}
} catch (Exception e) {
}
m.put(key, value);
}else if(v.isJsonObject()){
m.put(key,context.deserialize(v, Map.class));
}
}
return m;
}
})
.create();
return gson.fromJson(psiFile.getText(), TestDataModel.class);