Search code examples
javajsonjacksonclasscastexceptioncoercion

How do you parse JSON object keys as integers with Jackson?


I am deserializing a JSON into a Map<Integer, String>.

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

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())
{
    try
    {
        System.out.println("map: " + entry.getKey());
        int index = entry.getKey();
        System.out.println("map**: " + index);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

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

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.


Solution

  • 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).