java - 解决 JSONException 重复键

标签 java json google-search-api

我正在使用谷歌自定义搜索引擎并以 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 出现了多次

最佳答案

与其他任何对象一样,JSon 对象不能有两个同名的属性。这与在 map 中两次使用相同的键一样是非法的。

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

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

关于java - 解决 JSONException 重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4912386/

相关文章:

Java返回问题

ruby-on-rails - Sidekiq 排队 POST 创建参数。使用 JSON 或 ActionController::Parameters?

json - Google 的 "define: "是通过 API 实现的吗?

android - 我应该如何索引 Android 应用程序的内容

java - 没有固定 JSON 正文的 JAX-RS Restful POST

xml - 请求来自 Google Search API 的响应

java - 从多种格式的文件中提取文本并将其存储在 Elasticsearch 中

java - ImageView 填充空白 ViewPager Android

java - 为什么 JacksonJsonProvider 会忽略 MediaType 的参数?

c# - 如何在 .NET 7 中使用 System.Text.Json 序列化多级多态类型层次结构?