【问题标题】:Unterminated object when converting a String to JSON将字符串转换为 JSON 时未终止的对象
【发布时间】:2015-04-27 11:55:01
【问题描述】:

我正在使用 Android Studio,并且我有一个名为 sResponse 的字符串变量(如下)。根据调试器,它包含以下值:

 {
    "responseData": {
    "emotion":"",
    "lastinput":{actionResult={"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
    "answer":"Sorry, I did not understand.",
    "link": {
    "href":"",
    "target":""
    },
    "extraData": {

    },
    "responseSession": {
    "id":"c4a5ef257851a991eb32c69132c9",
    "transaction":"4"
    },
    "responseDetails": "null",
    "responseStatus": "200",
    "applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
    }
    }

当我尝试用这种方式初始化一个 JSONObject 时:

jResponse=new JSONObject(sResponse);

...在我的 Logcat 中出现以下异常:

>>>>>>>>>Thread EXCEPTION1: Response with invalid JSON format: , FrontendActivity.java L:421 ***** *org.json.JSONException: Unterminated object at character 502 of : sResponse

我怀疑 URL 中的 // 会造成问题。我不是转义 JSON 字符的专家。如何从前一个字符串中获取有效的 JSONObject?你能在我的方法中发现什么问题?

【问题讨论】:

  • 您的 json 格式不正确,请更正您的 json 响应中的 actionResult= 对象
  • 感谢@NambiNarayanan 指出错误,该值来自支持(也许是硬编码?),但请不要投票!
  • 好的,我删除了我的投票,但在以后发布之前检查您的问题。
  • @Josh 如果它对你有用,你应该接受正确的答案。

标签: java android json escaping jsonobject


【解决方案1】:

由于actionResult 附近的= 符号以及actionResult 没有用双引号括起来并且您没有正确关闭json 字符串而导致的问题。

将 Json 字符串替换为:

{
    "responseData": {
    "emotion":"",
    "lastinput":{"actionResult":{"value":{"label":"green","key":"1"},"result":"success","action":"displayClickableList"},
    "answer":"Sorry, I did not understand.",
    "link": {
    "href":"",
    "target":""
    },
    "extraData": {

    },
    "responseSession": {
    "id":"c4a5ef257851a991eb32c69132c9",
    "transaction":"4"
    },
    "responseDetails": "null",
    "responseStatus": "200",
    "applicationUrl": "http://noki-dev.cloud.com:90/role-va-1/"
    }
    }
}

并在字符串末尾添加}

您可以使用以下在线工具跟踪错误:

http://json.parser.online.fr/

【讨论】:

  • 谢谢,你在哪里,我已经挣扎了几个小时,我厚厚的眼睛就是看不到错误!它来自后端。
【解决方案2】:

您在响应结束时错过了最后一个结束卷曲。 只需在最后一行添加}

更正的 json 响应

{
  "responseData": {
    "emotion": "",
    "lastinput": {
      actionResult: {
        "value": {
          "label": "green",
          "key": "1"
        },
        "result": "success",
        "action": "displayClickableList"
      },
      "answer": "Sorry, I did not understand.",
      "link": {
        "href": "",
        "target": ""
      },
      "extraData": {

      },
      "responseSession": {
        "id": "c4a5ef257851a991eb32c69132c9",
        "transaction": "4"
      },
      "responseDetails": "null",
      "responseStatus": "200",
      "applicationUrl": "http://noki-dev.cloud.com:90/moto-1/"
    }
  }
}

【讨论】:

    猜你喜欢
    • 2019-10-10
    • 1970-01-01
    • 2019-08-27
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    • 2012-06-14
    • 2012-02-20
    相关资源
    最近更新 更多