简体   繁体   English

JSON:在JSON字符串中转义双引号

[英]JSON : Escape Double Quotes within JSON String

I have a JSON string like this : 我有一个像这样的JSON字符串:

 {
       "serviceName":"Data file "%s" was deleted successfully.",
       "serviceInstance":"esm-session-service"
     }

I am trying to map above JSON to object using ObjectMapper as below: 我正在尝试使用ObjectMapper将上面的JSON映射到对象,如下所示:

Message messageObject = objectMapper.readValue(messageJson, Message.class);

Below is stack trace output: 下面是堆栈跟踪输出:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('%' (code 37)): was expecting comma to separate Object entries
 at [Source: (String)"{"serviceName":"\"Data file \""%s"serviceInstance":"esm-session-service"}r""; line: 1, column: 33]
    at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:663)
    at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:561)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser._skipComma(ReaderBasedJsonParser.java:2271)
    at com.fasterxml.jackson.core.json.ReaderBasedJsonParser.nextFieldName(ReaderBasedJsonParser.java:892)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:295)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
    at com.test.json.TestJsonObjectConversion.main(TestJsonObjectConversion.java:77)

I know problem is with "%s" in the JSON, I am not able to find any way to escape quotes in only "%s". 我知道JSON中的“%s”存在问题,我无法找到任何仅在“%s”中转义引号的方法。

I am expecting below JSON: 我期望在JSON以下:

{
  "serviceName":"Data file \"%s\" was deleted successfully.",
  "serviceInstance":"esm-session-service"
}

Thanks in advance. 提前致谢。

The problem is stated as receiving an invalid JSON string from Elastic Search where double quotes are not escaped. 据说该问题是从Elastic Search接收到无效的JSON字符串,其中双引号未转义。

If you cannot find a correction by Elastic Search (looking for the latest version), a patch is in order: 如果您无法通过Elastic Search找到更正(正在寻找最新版本),请准备以下补丁

Assuming key value pairs occupy a single line: 假设键值对占据一行:

Since java 9: 从Java 9开始:

String json = ...;
json = json.replaceAll(":\\s*\"(.*)\"",
        (m) -> {
            String value = m.group(1);
            value = value.replaceAll("(?!\\)\"", "\\\\\");
            return ":\"" + value + "\"";
        });

This will fill value with the longest sequence between double quotes. 这将用双引号之间的最长序列填充value The negative lookahead (?!\\\\) checks that no backslash already precedes an inner double quote. 否定的前瞻(?!\\\\)检查内部双引号之前是否没有反斜杠。

Maybe better would be to overall escape the string value by Apache Common Text StringEscapeUtils : 也许更好的办法是使用Apache Common Text StringEscapeUtils对字符串值进行整体转义:

json = json.replaceAll(":\\s*\"(.*)\"",
        (m) -> ":\"" + StringEscapeUtils.escapeJson(m.group(1)) + "\"");

Prior to java 9 one would need a loop for the regex replace. 在Java 9之前,需要一个循环进行正则表达式替换。 If the key-value pairs are not on one line (like the value containing newlines) again the regex needs to do multiline, DOT_ALL. 如果键值对不在一行上(例如包含换行符的值),则正则表达式需要执行多行DOT_ALL。

The resulting JSON string can be passed, maybe via a StringReader. 可以通过StringReader传递生成的JSON字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM