-1

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?

learner
  • 1,381
  • 1
  • 10
  • 16

1 Answers1

1

You can use the general class Number

Number n = jsonObject.get("a");
long l = n.getLongValue();
Denis Lukenich
  • 3,084
  • 1
  • 20
  • 38