Reputation: 1381
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.
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?
Upvotes: -1
Views: 1606
Reputation: 3164
You can use the general class Number
Number n = jsonObject.get("a");
long l = n.getLongValue();
Upvotes: 1