我想使用Generic,因为我希望它能适应我遇到的很多情况,所以我使用泛型并且不想改变,这里的代码如下所示。
/**
* set json to map object
*
* @param jsonStr
* @return
*/
public static Map<?, ?> jsonToMap(String jsonStr) {
Map<?, ?> objMap = null;
Gson gs = new GsonBuilder()
.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
@Override
public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
if (src == src.longValue())
return new JsonPrimitive(src.longValue());
return new JsonPrimitive(src);
}
}).create();
if (gson != null) {
java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<Map<?, ?>>() {
}.getType();
objMap = gson.fromJson(jsonStr, type);
}
return objMap;
}
输入是:
{id = 1,level = 2,name = Tom,gender = 1} {id = 3,level = 4,name = Anny,gender = 2}
输出不是我想要的:
{id = 1.0,level = 2.0,name = Tom,gender = 1.0} {id = 3.0,level = 4.0,name = Anny,gender = 2.0}
在地图中有没有办法让整数而不是双打?
{id = 1,level = 2,name = Tom,gender = 1} {id = 3,level = 4,name = Anny,gender = 2}