首页 > 解决方案 > Java:来自 JSON 的数组数组

问题描述

我有一个 JSON Arrays of Array 像这样

"results": [
    {
        "id": "AAA",
        "color": "#4D4837",
        "links": {
            "self": "https://aaa.com",
            "html": "https://bbb.com",
            "download": "https://ccc.com",
            "download_location": "ddd.com"
        },
        "categories": [],
        "likes": 3891,

     },
    {
        "id": "BBB",
        "color": "#4D453",
        "links": {
            "self": "https://abb.com",
            "html": "https://bcc.com",
            "download": "https://ccc.com",
            "download_location": "ddd.com"
        },
        "categories": [],
        "likes": 3000,

     }
 ]

我想检索“ html”的“ https://bbb.com ”和“ https://bcc.com ”,但我不知道该怎么做。

基于善意的评论,我提出以下内容。不知何故,“getJSONObject()”不能放。错误消息显示“无法解析 'JSONArray' 中的方法 'getJSONObject'”。

JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
        for (int i =0 ; i<2 ; i++){
            JSONObject job = (JSONObject) array.get(i);   --> get(i) can not be changed to getJSONObject(i)
            String id = job.get("id").toString();
            String color = job.get("color").toString();
            String photoUrl = job.get("links").toString();  --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".

        }

但是当我尝试使用以下内容时,不仅会检索“html”,还会检索“self”和其他信息。

String photoUrl = job.get("links").toString();

请告诉我如何只检索“html”。

我正在使用 IntelliJ。

标签: javaarraysjson

解决方案


要遵循的步骤(假设您提到了正确的 JSONArray):

  1. 通过索引从您的 JSONArray 中获取 JSONObject,即。对于你的情况,index=0在这里
  2. 通过 key 获取内部 JSONObjectlinks
  3. 现在,通过以下键访问您的内容html

您的案例示例:

JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");

最好按照 Harshal 的建议继续检查密钥是否存在


推荐阅读