[英]fastjson java.lang.Integer cannot be cast to java.lang.Long
I have a code snippet我有一个代码片段
Map<String, Object> map = new HashMap<>();
map.put("a", new Long(11L));
String jsonStr = JSONObject.toJSONString(map);
System.out.println("jsonStr : " + jsonStr);
JSONObject jsonObject = JSON.parseObject(jsonStr);
Long a = (Long) jsonObject.get("a");
System.out.println("a : " + a);
then, it throws exception:然后,它抛出异常:
java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
for some reason, I can only use jsonObject.get.出于某种原因,我只能使用 jsonObject.get。
so, I have to change the code to:所以,我必须将代码更改为:
Map<String, Object> map = new HashMap<>();
map.put("a", new Long(11L));
String jsonStr = JSONObject.toJSONString(map);
System.out.println("jsonStr : " + jsonStr);
JSONObject jsonObject = JSON.parseObject(jsonStr);
// Long a = (Long) jsonObject.get("a");
Object a = jsonObject.get("a");
Long aa;
if (a instanceof Integer) {
aa = Long.valueOf((Integer)a);
} else if (a instanceof Long) {
aa = (Long)a;
}
System.out.println("a : " + aa);
Do I have any other better way to parse the Long value 11L with FastJson?我还有其他更好的方法来使用 FastJson 解析 Long 值 11L 吗?
You can use the general class Number您可以使用通用类 Number
Number n = jsonObject.get("a");
long l = n.getLongValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.