【问题标题】:Escape JSON string in Java在 Java 中转义 JSON 字符串
【发布时间】:2018-07-03 03:54:30
【问题描述】:

我使用的是 Google 的 com.google.api.client.json.GenericJsoncom.fasterxml.jackson.core.JsonGenerator。我想序列化 JSON 对象并转义引号和反斜杠,以便我可以在 Bash 中传递该字符串。然后反序列化该字符串。

GenericJson.toString 生成简单的 JSON,但 \n 等不会被转义:

{commands=ls -laF\ndu -h, id=0, timeout=0}

有没有一种简单的方法可以得到这样的东西:

"{commands=\"ls -laF\\ndu -h\", id=0, timeout=0}"

我不想重新发明轮子,所以如果可能的话,我想使用 Jackson 或现有的 API。

【问题讨论】:

标签: java json jackson


【解决方案1】:

无需其他依赖项:您正在寻找JsonStringEncoder#quoteAsString(String)

点击JsonStringEncoder javadoc

示例:

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}"

参考:http://fasterxml.github.io/jackson-core/javadoc/2.1.0/com/fasterxml/jackson/core/io/JsonStringEncoder.html

【讨论】:

  • 我认为您在第一个代码块中的意思是“quoteAsString”而不是“quoteAsJson”?
  • 嗯,他给出的例子是一个 Json 块。但是,是的,其中之一。
【解决方案2】:

使用Gson 进行序列化被证明是非常简单且安全的。之后使用 Apache 的 commons-lang3 = 3.1 escapeEcmaScript。在3.2 中还有escapeJson 方法。

import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;

public class MyJson extends GenericJson {

    @Key("commands")
    public String commands;

    public String serialize() throws IOException {
      Gson gson = new Gson();
      String g = gson.toJson(this);
      return StringEscapeUtils.escapeEcmaScript(g);
    }
}

这会产生转义的 JSON:

{\"commands\":\"ls -laF\\ndu -h\"}

那么反序列化就很简单了:

protected MyJson deserialize(String str) throws IOException {
    String json = StringEscapeUtils.unescapeEcmaScript(str);
    JsonObjectParser parser = (new JacksonFactory()).createJsonObjectParser();
    return parser.parseAndClose(new StringReader(json), MyJson.class);
}

escapeEcmaScript 方法并不复杂,它做了以下替换:

  {"'", "\\'"},
  {"\"", "\\\""},
  {"\\", "\\\\"},
  {"/", "\\/"}

但至少是我不必关心的事情。

【讨论】:

  • escapeJson 是从 StringEscapeUtils() 访问的,现在已弃用。
猜你喜欢
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 2012-05-18
  • 2012-08-30
  • 2021-09-23
  • 2014-01-31
相关资源
最近更新 更多