【发布时间】:2015-02-04 18:01:42
【问题描述】:
在我的 grails 应用程序中,我正在调用第三方 REST api,它返回 JSON,其中我可能将 HTML 内容作为属性值。例如,像这样:
{
"presentationData": {
"id": "123-45",
"placeholders": [
{
"transition": "fade",
"items": [
{
"name": "Text Item",
"objectData": "<font face=\\"Palatino Linotype, Book Antiqua, Palatino, serif\\" size=\\"7\\">TEXT TEXT TEXT</font>",
"timeDefined": "false"
}
]
}
]
}
}
我无法在 grails 中解析此 JSON:在以下位置出现异常:
"objectData": "<font face=\\"Palatino Linotype, Book Antiqua, Palatino, serif\\" size=\\"7\\">TEXT TEXT TEXT</font>",
由于值中有\\ 个字符。
我试过下面的代码:
JSONElement scriptJson=JSON.parse(resp)
甚至使用 JsonSlurper:
JsonSlurper slurper=new JsonSlurper()
def scriptJson=slurper.parseText(resp)
两者都以相同的值失败。
我尝试在解析之前将\\ 替换为\,但无法正常工作:
resp=resp.replaceAll(/\\+/,/\/)
出现编译错误,好像我尝试用任何其他字符替换,#,而不是 / 它被替换:
resp=resp.replaceAll(/\\+/,/#/)
输出为:
<font face=#"Palatino Linotype, Book Antiqua, Palatino, serif#" size=#"7#">TEXT TEXT TEXT</font>
所以我需要解决方案:
解析这个无效的 JSON 或在 groovy 中将 \\ 替换为 \。
过去两天我一直在为此苦苦挣扎。请帮帮我。
【问题讨论】:
-
试试 resp=resp.replaceAll(/\\+/,/'/)
-
@BZ,它正在替换为单引号
'。但我想用单反斜杠`\`代替。我想我在我的问题中也表达了同样的意思。