我使用以下格式获取String,这在使用Jackson ObjectMapper readTree api进行语法分析时会导致问题。用于解析给定String的代码是
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
JsonNode rootNode = objectMapper.readTree(inputString);
在下面的String
中遇到“7”时抛出异常{
OBJECT_CONVERSION_ERROR:"Failed..."
Portal:{
7061:"User is....."}
}
如何使用JAVA以有效JSON格式转换此类字符串? 我正在使用jackson-all-1.9.11.jar
以下是我的异常消息
org.codehaus.jackson.JsonParseException:意外的字符('7'(代码55)):期望有效的名称字符(对于不带引号的名称)或双引号(对于引用)来启动字段名称 在[来源:java.io.StringReader@3fb1549b; line:1,column:1433]
在将输入字符串传递给Object Mapper进行解析之前,有没有办法将输入字符串转换为有效的json格式?
答案 0 :(得分:0)
Jackson ObjectMapper在默认配置中需要双引号字段名称。
要更改此行为,您可以执行以下操作:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
答案 1 :(得分:-1)
JSONParser parser = new JSONParser(); JSONObject json = (JSONObject)
parser.parse(stringToParse);
了解详情:http://www.java67.com/2016/10/3-ways-to-convert-string-to-json-object-in-java.html#ixzz4y2fACQlg