反序列化String时的org.codehaus.jackson.JsonParseException

时间:2018-11-19 07:36:46

标签: java deserialization objectmapper fasterxml

我在资源文件中有以下字符串,并且我正在尝试使用ObjectMapper反序列化为Map

  

{13714974:{get-url:“ https://example.com/get”,后URL:   “ https://example.com/post”},13743772:{get-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

我也尝试了更快的XML ObjectMapper,但是它不起作用

那我该如何调试字符串到地图上?

1 个答案:

答案 0 :(得分:0)

这是我们反序列化上述字符串的方式

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    
}