我正在尝试使用com.fasterxml.jackson.databind.ObjectMapper
做一件简单的事情。
我有一个对象想要转换为String
。
class Car{
String color;
String brand;
//... more class info
}
它工作正常,我得到了我的 String
,但结果如下所示:
{"color: "blue", "brand": "toyota" }
是否可以使其看起来像:
{\"color\": \"blue\", \"brand\", \"toyota\" }
我不确定这是否破坏了 JSON
预期格式。
我已经阅读了文档,似乎我可以使用这个:
ObjectMapper().factory.setCharacterEscapes(...)
但我不确定如何传递它或从哪个存储库传递它。有什么想法吗?
最佳答案
使用Jackson
生成有效的JSON
负载和StringEscapeUtils来逃避它。
示例代码:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.text.StringEscapeUtils;
public class EscapeJsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new Car("blue", "Toyota"));
String escapedJson = StringEscapeUtils.escapeJson(json);
System.out.println(escapedJson);
}
}
class Car {
String color;
String brand;
// getters, setters, constructor
}
上面的代码打印:
{\"color\":\"blue\",\"brand\":\"Toyota\"}
Maven dependency :
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.8</version>
</dependency>
关于java - 如何向我的 JSON 映射器引入转义字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846351/