Search code examples
javadeserializationobjectmapperfasterxml

org.codehaus.jackson.JsonParseException while deserialising String


I have the following string in a resource file and I am trying to deserialise to Map using ObjectMapper

{ 13714974: { get-url: "https://example.com/get", post-url: "https://example.com/post" }, 13743772: { get-url: "https://example.com/get", post-url: "https://example.com/post" }

ObjectMapper mapper = new ObjectMapper();
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        Map<String, Map<String, String>> cmMappings = mapper.readValue(content, Map.class);

When I use codehaus jackson ObjectMapper and try to deserialise it, I get the exception,

Exception in thread "main" org.codehaus.jackson.JsonParseException: Unexpected character ('1' (code 49)): was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name
 at [Source: java.io.StringReader@7cdbc5d3; line: 1, column: 3]
    at org.codehaus.jackson.impl.JsonParserBase._constructError(JsonParserBase.java:651)
    at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:635)
    at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:576)
    at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:385)
    at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:268)
    at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:118)

and when running the code to deserialise a resource file containing string of this format I get Exception while deserialising because of hyphen in field names.

I tried fasterxml ObjectMapper also but it does not work

So how do I debug the string to the map ?


Solution

  • This is how we deserialise the above String

    try {    
        ObjectMapper mapper = new ObjectMapper();
        ClassPathResource resource = new ClassPathResource("resourceFile");
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        TypeReference<HashMap<String, Map<String, String>>> typeRef = new TypeReference<HashMap<String, Map<String, String>>>() {};
        cmMappings = mapper.readValue(resource.getInputStream(), typeRef);
    } catch (Exception ex) {
       // log error    
    }