【问题标题】:fastjson java.lang.Integer cannot be cast to java.lang.Longfastjson java.lang.Integer 不能转换为 java.lang.Long
【发布时间】:2018-09-30 07:19:17
【问题描述】:

我有一个代码 sn-p

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);

然后,它抛出异常:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

由于某种原因,我只能使用 jsonObject.get。

所以,我必须将代码更改为:

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);

我还有其他更好的方法来使用 FastJson 解析 Long 值 11L 吗?

【问题讨论】:

标签: java fastjson


【解决方案1】:

可以使用通用类 Number

Number n = jsonObject.get("a");
long l = n.getLongValue();

【讨论】:

    猜你喜欢
    • 2021-07-21
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 2013-08-24
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多