4

我正在使用谷歌自定义搜索引擎并以 JSON 格式获取结果。对于某些查询,JSON 结果具有重复键,因此会产生 JSONException:重复键“昵称”等。

我正在使用 JAVA。

String str=//contains the query result in json format
JSONObject ob=new JSONObject(str) produces the exception

可能知道如何解决这个异常?

这是 JSON 回复:

{
   "kind": "customsearch#result",
   "title": "The World Factbook: India - CIA - The World Factbook",
   "htmlTitle": "The World Factbook: \u003cb\u003eIndia\u003c/b\u003e -",
   "link": "https://www.cia.gov/library/publications/the-world-factbook/geos/in.html",
   "displayLink": "www.cia.gov",
   "snippet": "Jan 20, 2011 ... Features a map and brief descriptions of geography",
   "htmlSnippet": "Jan 20, 2011 \u003",
   "cacheid": "0n2U45w_dvkJ",
   "pagemap": {
    "metatags": [
     {
      "il.secur.classif": "UNCLASSIFIED",
      "il.title": "(U) CIA The World Factbook",
      "il.summary": "CIA - The World Factbook",
      "il.cutdate": "20040101",
      "il.secur.classif": "UNCLASSIFIED",
      "il.title": "(U) CIA The World Factbook",
      "il.cutdate": "20040101",
      "il.secur.classif": "UNCLASSIFIED",
      "il.pubdate": "20040101",
      "il.postdate": "20040501",
      "il.cutdate": "20040101"
     }
    ]
   }
  }

这里 il.secur.classif 出现多次

4

3 回答 3

7

JSON 对象与任何其他对象一样,不能有两个同名的属性。这与在地图中拥有两次相同的键相同是非法的。

如果一个对象中有两个同名的键,JSONObject 会抛出异常。您可能想要更改您的对象,以便键不会在同一对象下重复。可能被认为nickname是一个数组。

您需要将 JSON 对象粘贴到问题中。

于 2011-02-06T08:59:18.673 回答
0

如果你真的需要这个功能,回滚到 gson 1.6。该版本允许重复密钥。

于 2012-10-11T17:59:03.890 回答
0

您可以使用 Jackson 库来解析 JSON。使用 org.json 的包执行与您相同的任务时,我会遇到问题,但我求助于杰克逊并解决了它:http ://wiki.fasterxml.com/JacksonHome

于 2014-12-04T12:42:39.313 回答