Jackson ObjectMapper writeValueAsBytes 方法向已经包含反斜杠的字符串添加另一个反斜杠
Jackson ObjectMapper writeValueAsBytes method adds another backslash to a string that already contains backslash
如果我尝试使用 Jacksons 的 ObjectMapper 将已经包含反斜杠的字符串转换为字节数组,然后将该字节数组改回字符串,则输出包含一个额外的反斜杠。下面的代码显示了问题
public static void main(String[] args) throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> data = new HashMap<>();
data.put("id", "Test\String");
//output: data[id] that has single backslash: Test\String
System.out.println("data[id] that has single backslash: " + data.get("id"));
byte[] dataInBytes = mapper.writeValueAsBytes(data);
//output: data in bytes that contains double backslash: {"id":"Test\String"}
System.out.println("data in bytes that contains double backslash: " + new String(dataInBytes, "UTF-8"));
}
有没有办法配置 ObjectMapper,使 mapper#writeValueAsBytes 方法不会将字符串 Test\String 更改为 Test\\String?还有其他方法可以使用 Jackson/ObjectMapper 来实现吗?
提前致谢!!
这是有效的行为。输出具有 转义反斜杠 。在 JSON 中,反斜杠必须转义。
换句话说,{"id":"Test\String"}
无效 JSON。
检查 this 在 JSON 中必须转义的其他字符。
如果我尝试使用 Jacksons 的 ObjectMapper 将已经包含反斜杠的字符串转换为字节数组,然后将该字节数组改回字符串,则输出包含一个额外的反斜杠。下面的代码显示了问题
public static void main(String[] args) throws JsonProcessingException, UnsupportedEncodingException {
ObjectMapper mapper = new ObjectMapper();
Map<String, String> data = new HashMap<>();
data.put("id", "Test\String");
//output: data[id] that has single backslash: Test\String
System.out.println("data[id] that has single backslash: " + data.get("id"));
byte[] dataInBytes = mapper.writeValueAsBytes(data);
//output: data in bytes that contains double backslash: {"id":"Test\String"}
System.out.println("data in bytes that contains double backslash: " + new String(dataInBytes, "UTF-8"));
}
有没有办法配置 ObjectMapper,使 mapper#writeValueAsBytes 方法不会将字符串 Test\String 更改为 Test\\String?还有其他方法可以使用 Jackson/ObjectMapper 来实现吗?
提前致谢!!
这是有效的行为。输出具有 转义反斜杠 。在 JSON 中,反斜杠必须转义。
换句话说,{"id":"Test\String"}
无效 JSON。
检查 this 在 JSON 中必须转义的其他字符。