Jacco Jacco - 2 months ago 7
JSON Question

ClassCastException while trying to cast Object to MapEntry

I'm trying to get some values from a JSONObject into a HashMap, but I keep getting ClassCastException on the last row of my for loop.

Exception in thread "main" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer


I've tried to explicitly cast mapEntry.getValue() to integer but I keep getting the same error. if I run the code without the last line I get the following output:

key: peter value: 33
key: somekey value: 11
key: steve value: 38
key: guy value: 22
key: name value: 54


So I can see that mapEntry.getValue() seems to print integers, or at the very least numbers that I should be able to cast to integers.

JSONObject json = getJsonFromFile(filePath);
HashMap<String, Integer> entries = new HashMap<>();

for (Object obj : json.entrySet()) {
Entry<String, Integer> mapEntry = (Entry<String, Integer>) obj;
System.out.println("key: " + mapEntry.getKey() + " value: " + mapEntry.getValue());
entries.put(mapEntry.getKey(), mapEntry.getValue());
}

Answer

If you try this:

JSONObject json = getJsonFromFile(filePath);
HashMap<String, Number> entries = new HashMap<>();

for (Object obj : json.entrySet()) {
    Entry<String, Number> mapEntry = (Entry<String, Number>) obj;
    System.out.println("key: " + mapEntry.getKey() + " value: " + mapEntry.getValue());
    entries.put(mapEntry.getKey(), mapEntry.getValue());
}

Number is the superclass of both Integer and Long, it should compile fine.

Comments