【问题标题】:JSON parsing in GrailsGrails 中的 JSON 解析
【发布时间】: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": "&lt;font face=\\"Palatino Linotype, Book Antiqua, Palatino, serif\\" size=\\"7\\"&gt;TEXT TEXT TEXT&lt;/font&gt;",

由于值中有\\ 个字符。

我试过下面的代码:

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,它正在替换为单引号'。但我想用单反斜杠`\`代替。我想我在我的问题中也表达了同样的意思。

标签: regex json grails groovy


【解决方案1】:

好的。经过几次试验和错误,终于成功了:

resp.replaceAll(/\\+/,'\\\\')

输出如下:

<font face=\"Palatino Linotype, Book Antiqua, Palatino, serif\" size=\"7\">TEXT TEXT TEXT</font>

现在JSON.parse(resp)slurper.parseText(resp) 都可以正常工作,没有任何错误。

我仍然认为可能有比这更好的解决方案。无论如何,我现在没有太多时间,所以我要使用这个解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 2012-06-02
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2011-07-07
    相关资源
    最近更新 更多