代码之家  ›  专栏  ›  技术社区  ›  Aarish Ramesh

反序列化字符串时发生org.codehaus.jackson.JsonParseException

  •  0
  • Aarish Ramesh  · 技术社区  · 7 年前

    {13714974:{获取url: https://example.com/get “,发布url: https://example.com/post },13743772:{获取url: " https://example.com/get 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);
    

    当我使用codehaus jackson ObjectMapper并尝试反序列化它时,我得到了一个异常,

    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)
    

    Exception while deserialising because of hyphen in field names

    我也尝试了FasterXMLObjectMapper,但它不起作用

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ashish Kamble    7 年前

    这就是我们如何反序列化上面的字符串

    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    
    }