Nav Nav - 1 year ago 186
JSON Question

JSON Loading in Java: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

I'm trying out the example from here, and am using this code to write to a file:

public void Write() {

FileWriter file = null;
try {
JSONObject o = new JSONObject();
JSONObject obj = new JSONObject();
obj.put("name", "");
obj.put("age", new Integer(100));
JSONObject obj2 = new JSONObject();
obj2.put("name", "");
obj2.put("age", new Integer(1800));
file = new FileWriter(filename);
JSONArray list = new JSONArray();

o.put("messages", list);

} catch (IOException ex) {logger.error("{}", ex.getCause());} finally {try {file.close();} catch (IOException ex) {"{}",ex.getCause());}}

and using this code to read from the same file:

public void Load() {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(new FileReader(filename));
} catch (IOException | ParseException ex) {"{}", ex.getCause());}
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<JSONObject> iterator = msg.iterator();
while (iterator.hasNext()) {
JSONObject ob =;
String name =(String) ob.get("name");
Integer age =(Integer) ob.get("age");"name: {}, age: {}", name, age);

But although the data is written successfully as
, I have trouble while loading.
At this line
Integer age =(Integer) ob.get("age");
the compiler says "Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer".

I tried casting in multiple ways, but it doesn't work. Why does such an error happen?

ps: I'm using
compile group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1'

Answer Source

When you write your json file all additional information is lost (in your case the Integer type you used. When you read it the JSONParser will automatically use Long when it encounters a number without decimal points. Try using Long in your reader. Note that the reader knows nothing about the writer. It can only read a file and interpret it as it sees fit.

So to answer your question:

Long age =(Long) ob.get("age");

will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download