在Java中转义JSON字符串 [英] Escape JSON string in Java
问题描述
我正在使用Google的 com.google.api.client.json.GenericJson
和 com.fasterxml.jackson.core.JsonGenerator
。我想序列化JSON对象并转义引号和反斜杠,以便我可以在Bash中传递该字符串。然后反序列化该字符串。
I'm using Google's com.google.api.client.json.GenericJson
and com.fasterxml.jackson.core.JsonGenerator
. I would like to serialize JSON object and escape quotes and backslashes so that I can pass that string in Bash. And afterwards deserialize that string.
GenericJson.toString
生成简单的JSON,但 \ n
等未被转义:
GenericJson.toString
produces simple JSON, but \n
etc. are not escaped:
{commands=ls -laF\ndu -h, id=0, timeout=0}
有一种简单的方法可以得到这样的结果:
is there a simple way how to get something like this:
"{commands=\"ls -laF\\ndu -h\", id=0, timeout=0}"
我不想重新发明轮子,所以我想用杰克逊或者现有的API,如果可能的话。
I don't want to reinvent the wheel, so I'd like to use Jackson or an existing API, if possible.
推荐答案
不需要其他依赖项:您正在寻找 JsonStringEncoder #quoteAsString(String)
。
No additional dependencies needed: You're looking for JsonStringEncoder#quoteAsString(String)
.
import com.fasterxml.jackson.core.io.JsonStringEncoder;
JsonStringEncoder e = JsonStringEncoder.getInstance();
String commands = "ls -laF\\ndu -h";
String encCommands = new String(e.quoteAsString(commands));
String o = "{commands: \"" + encCommands + "\", id: 0, timeout: 0}"
这篇关于在Java中转义JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!