Search code examples
javajacksonjackson-databind

ClassCastException while access Map entry


I am facing a problem I do not understand.

I have created a small example.

package com.demo;
import java.util.Map;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DemoTest {

    @Test
    public void test1() throws Exception {
        String json = "{" + "\"a\": \"a1\"," + "\"b\": {" + "\"bb\": \"b1\"" + "}" + "}\"";

        final ObjectMapper mapper = new ObjectMapper();
        Map<String, String> myMap = mapper.readValue(json, Map.class);

        String contentA = myMap.get("a");
        System.out.println(contentA);
        String contentB = myMap.get("b");
        System.out.println(contentB);
    }
}

Pretty print of the json string

{
    "a": "a1",
    "b": {
        "bb": "b1"
    }
}

The line System.out.println(contentA); produce
a1

The line System.out.println(contentB); produce

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class java.lang.String (java.util.LinkedHashMap and java.lang.String are in module java.base of loader 'bootstrap') at com.demo.DemoTest.test1(DemoTest.java:20)

While debugging the object myMap I see:

{a=a1, b={bb=b1}}  
[0]: {a=a1, b={bb=b1}}  
[1]: b={bb=b1}

I do not understand why {bb=b1} is handled as a Map

I appreciate your help.


Solution

  • The value of “b” is not a string but the (inner) json. So you can’t really convert it to string. Jackson tries to address this inner json by converting it to LinkedHashMap but it can’t be put into myMap’s value which must be a string. LinkedHashMap cannot be casted to String hence the error

    I suggest using JsonNode as a target of conversion

    ObjectMapper mapper = new ObjectMapper();
    JsonNode actualObj = mapper.readTree(json);