【问题标题】:Get values out of JSON (Map<String, Object>) with JSONObject使用 JSONObject 从 JSON (Map<String, Object>) 中获取值
【发布时间】:2023-03-25 11:19:01
【问题描述】:

是否可以使用 JSONObject、JSONArray、getString() (org.json) 从下面的 JSON 示例(假设为字符串结果)中获取所有值(linkIDtextoptions) Java中的库?如果是的话,谁能举个例子。

"items": [
        {
            "linkID": "my/link1",
            "text": "Some text 1.",
            "options": [
                "yes",
                "no",
                "maybe",
                "always"
            ]
        },
        {
            "linkID": "my/link2",
            "text": "Some text 2.",
            "options": [
                "yes",
                "no",
                "maybe",
                "always"
            ]
        }
    ]

更新:

我在上面找到了一个解决方案。如果有更好的请告诉我。

JSONArray items = json.getJSONArray("items");
        for (int i = 0; i < items.length(); ++i) {
            JSONObject rec = items.getJSONObject(i);
            String linkID = rec.getString("linkID");
            System.out.println(linkID);
            String text = rec.getString("text");
            System.out.println(text);
            JSONArray options = rec.getJSONArray("options");
            System.out.println(options);
}

如果我在 JSON 有效负载中有 2 个具有相同名称的键 code,我能否在下面的示例中获得具有值 61377 的内部 code

"code": {
           "code": "61377",
           "result": "ok"
           "info": "Some text"
    },

【问题讨论】:

    标签: java json


    【解决方案1】:

    是的,你可以通过这样做得到内部字段code的值,

    jsonObject.optJSONObject("code").optString("code")
    

    jsonObject 在哪里,

    "code": {
               "code": "61377",
               "result": "ok"
               "info": "Some text"
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多