gson的HashMapDeserializer

做个标记.

public class HashMapDeserializer implements
JsonDeserializer<HashMap<String, Object>> {

public HashMap<String, Object> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
// TODO Auto-generated method stub
if (json.isJsonNull()) {
return null;
} else if (json.isJsonPrimitive()) {
return null;
} else if (json.isJsonArray()) {
return null;
} else {
return (HashMap<String, Object>) handleObject(json, context);
}
}

private Object deserialize(JsonElement json,
JsonDeserializationContext context) throws JsonParseException {
// TODO Auto-generated method stub
if (json.isJsonNull()) {
return null;
} else if (json.isJsonPrimitive()) {
return handlePrimitive(json);
} else if (json.isJsonArray()) {
return handleArray(json, context);
} else {
return (HashMap<String, Object>) handleObject(json, context);
}
}

private Object handlePrimitive(JsonElement jsonEle) {
JsonPrimitive json = jsonEle.getAsJsonPrimitive();
if (json.isBoolean())
return json.getAsBoolean();
else if (json.isString()) {
String str = json.getAsString();

return json.getAsString();
} else {
BigDecimal bigDec = json.getAsBigDecimal();
try {
bigDec.toBigIntegerExact();
try {
return bigDec.intValueExact();
} catch (ArithmeticException e) {
}
return bigDec.longValue();
} catch (ArithmeticException e) {
}
return bigDec.doubleValue();
}
}

private Object handleArray(JsonElement jsonEle,
JsonDeserializationContext context) {
JsonArray json = jsonEle.getAsJsonArray();
List<Object> list = new ArrayList<Object>(json.size());
for (int i = 0; i < list.size(); i++) {
list.add(deserialize(json.get(i), context));
}
return list;
}

private Map<String, Object> handleObject(JsonElement json,
JsonDeserializationContext context) {
Map<String, Object> map = new HashMap<String, Object>();
for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject()
.entrySet()) {
JsonElement ele = (JsonElement) entry.getValue();
if (ele.isJsonNull()) {
map.put(entry.getKey(), null);
} else if (ele.isJsonPrimitive()) {
map.put(entry.getKey(), handlePrimitive(ele));
} else if (ele.isJsonArray()) {
map.put(entry.getKey(), handleArray(ele, context));
} else {
map.put(entry.getKey(), handleObject(ele, context));
}
}
return map;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值