Heisenberg Heisenberg - 11 months ago 63
JSON Question

ClassCastException : java.lang.String cannot be cast to java.lang.Integer

I am deserializing a JSON into a

Map<Integer, String>

But I am getting the above classCastException if I try to assign a
to primitive

ObjectReader reader = new ObjectMapper().reader(Map.class);
String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
Map<Integer, String> map = reader.readValue(patternMetadata);
System.out.println("map: " + map);
for (Map.Entry<Integer, String> entry : map.entrySet())
System.out.println("map: " + entry.getKey());
int index = entry.getKey();
System.out.println("map**: " + index);
catch (Exception e)

I am getting this
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
exception on second line in

I even tried changing
int index = enty.getKey().intValue()
. But still the same exception occurs.

P.S.: I am running it in an Android studio using Robolectric framework.


Those keys aren't integers, they're strings. Note the quotes on them:

String patternMetadata = "{\"1\":\"name\", \"2\":\"phone\", \"3\":\"query\"}";
// ------------------------^^-^^-----------^^-^^------------^^-^^

If this is JSON (it seems to be), object property names are always strings.

You'll need a Map<String, String> and then you'll need to parse the keys to int explicitly (if needed).