我有一个输入json字符串,包含一些已经转义的特殊字符和一些不转义的特殊字符(如en-破折号/em-破折号)。解析此json字符串(需要解析此字符串以检索对象数组)之后,它将具有特殊字符的字符串转换为Unicode值(例如,en-破折号字符为\u 2013)。我的要求是不要转义任何特殊的字符,并保持其他已经转义的字符。简单地说,在解析JSON字符串之后,内容不应该改变。
请建议一些方法来处理这件事。
解析之后,我尝试使用StringEscapeUtils取消它的转义。但它正在改变甚至另一个特殊的角色。一种方法是搜索字符串,如果包含任何unicode字符,并且只转义该部分。但特殊字符不是固定的。它可以是任何东西。
示例:
{
"orders": [
{
"name": "hello–world\ntext",
"type": "text\n"
},
{
"name": "hello",
"type": "text"
}
]
}对于上面的字符串,当我使用org.json.simple进行解析时,它是将endash字符转义到"hello\u2013world\ntext"作为name字段。有没有办法在解析时限制特殊字符的转义。
发布于 2019-10-08 06:37:12
您可能没有正确地解析JSON。我尝试使用ObjectMapper将提供的JSON解析为Map (您也可以使用class ):
String json = "{\n" +
" \"orders\": [\n" +
" {\n" +
" \"name\": \"hello–world\\ntext\",\n" +
" \"type\": \"text\\n\"\n" +
" },\n" +
" {\n" +
" \"name\": \"hello\",\n" +
" \"type\": \"text\"\n" +
" }\n" +
" ]\n" +
"}";对于未格式化的json,如下所示:
String json = "{\"orders\":[{\"name\":\"hello–world\\ntext\",\"type\":\"text\\n\"},{\"name\":\"hello\",\"type\":\"text\"}]}";使用ObjectMapper解析json:
ObjectMapper objectMapper = new ObjectMapper(); // package: com.fasterxml.jackson.databind
Map map = objectMapper.readValue(json, Map.class); // reading JSON as Map现在,如果我们打印map:
System.out.println(map);它打印:
{orders=[{name=hello–world
text, type=text
}, {name=hello, type=text}]}您可以看到它为
\n打印了一个新行。
现在,如果我们打印map的实际值:
System.out.println(objectMapper.writeValueAsString(map));它打印:
{"orders":[{"name":"hello–world\ntext","type":"text\n"},{"name":"hello","type":"text"}]}https://stackoverflow.com/questions/58280910
复制相似问题