Groovy JsonSlurper JSON 带有转义引号的值

Groovy JsonSlurper JSON value with escaped quotation marks

我正在开发一个用 Groovy 编写的小工具,它可以解析电子邮件中的 JSON 字符串。其中一些 JSON 字符串的 JSON 值包含转义引号。

例如:

{
   "hello": "world with \"quotation marks\""
}

为了解析这些字符串,我使用了 Groovy 的 JsonSlurper。以下代码演示了我的问题:

import groovy.json.JsonException
import groovy.json.JsonSlurper

try {     
  print new JsonSlurper().parseText('''
    {
      "hello": "world with \"quotation marks\""
    }
  ''')
} catch (JsonException | IllegalArgumentException e) {
  print e
}

请参阅 https://groovyconsole.appspot.com/script/6193189027315712 观看现场演示。

执行这段代码时,抛出以下异常:

groovy.json.JsonException: expecting '}' or ',' but got current char 'q' with an int value of 113

The current character read is 'q' with an int value of 113
expecting '}' or ',' but got current char 'q' with an int value of 113
line number 3
index number 35
      "hello": "world with "quotation marks""
............................^

因此,JsonSlurper 忽略引号的转义。不幸的是,我无法控制输入,即 JSON 字符串。因此,我必须找到一种方法将这样的 JSON 字符串解析为映射或任何其他合适的数据结构。

json 中的字符串未正确转义。文本数据应该是这样的:

'''
{
"hello": "world with \\"quotation marks\\""
}
'''

您收到的字符串表明邮件正文包含 json 格式: { "hello": "world with "quotation marks"" } 虽然它应该像 { "hello": "world with \"quotation marks\"" } 如果之前是这种情况,那么您无法解析无效的 json,因为代码无法识别转义数据。