Nav
Nav

Reputation: 20668

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", "mky4ong.com");
            obj.put("age", new Integer(100));
            JSONObject obj2 = new JSONObject();
            obj2.put("name", "mk54yong.com");
            obj2.put("age", new Integer(1800));
            file = new FileWriter(filename);
            JSONArray list = new JSONArray();
            list.add(obj);
            list.add(obj2);

            o.put("messages", list);

            file.write(o.toJSONString());
            file.flush();
            file.close();
        } catch (IOException ex) {logger.error("{}", ex.getCause());} finally {try {file.close();} catch (IOException ex) {logger.info("{}",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) {logger.info("{}", ex.getCause());}
    JSONObject jsonObject = (JSONObject) obj;
    JSONArray msg = (JSONArray) jsonObject.get("messages");
    Iterator<JSONObject> iterator = msg.iterator();
    while (iterator.hasNext()) {
        JSONObject ob = iterator.next();
        String name =(String) ob.get("name");
        Integer age =(Integer) ob.get("age");
        logger.info("name: {}, age: {}", name, age);
    }
}
}

But although the data is written successfully as {"messages":[{"name":"mky4ong.com","age":100},{"name":"mk54yong.com","age":1800}]}, 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'

Upvotes: 4

Views: 6069

Answers (1)

Adam Arold
Adam Arold

Reputation: 30548

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.

Upvotes: 6

Related Questions