gpt4 book ai didi

java - 如何从java中的JSONObject获取所有键/子键?

转载 作者:行者123 更新时间:2023-11-30 02:11:59 25 4
gpt4 key购买 nike

这是我的 JSONObject :

{
"per_page": 3,
"total": 12,
"data": [{
"color": "#98B2D1",
"year": 2000,
"name": "cerulean",
"id": 1,
"pantone_value": "15-4020"
}, {
"color": "#C74375",
"year": 2001,
"name": "fuchsia rose",
"id": 2,
"pantone_value": "17-2031"
}
],
"page": 1,
"total_pages": 4
}

从中我应该得到所有的键,包括per_pagetotaldatacolor年份pantone_value名称total_pages

如果我使用 JSONObject.names() 或 JSONObject.keySet() 。我只得到最外面的键

最佳答案

package com.samples;

import java.util.Iterator;

import gvjava.org.json.JSONArray;
import gvjava.org.json.JSONException;
import gvjava.org.json.JSONObject;

public class JSONObjectSample {

public static void main (String [] args) {
String jsonString = new String("{\"per_page\": 3,\"total\": 12,\"data\": [{\"color\": \"#98B2D1\",\"year\": 2000,\"name\": \"cerulean\",\"id\": 1,\"pantone_value\": \"15-4020\" }, {\"color\": \"#C74375\",\"year\": 2001,\"name\": \"fuchsia rose\",\"id\": 2,\"pantone_value\": \"17-2031\" }], \"page\": 1,\"total_pages\": 4 }\r\n");
try {
JSONObject jsonObject = new JSONObject(jsonString);
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
System.out.println(key);
if(jsonObject.get(key) instanceof JSONArray) {
JSONArray array = (JSONArray) jsonObject.get(key);
JSONObject object = (JSONObject) array.get(0);
Iterator<String> innerKeys = object.keys();
while(innerKeys.hasNext()) {
String innerKey = innerKeys.next();
System.out.println(innerKey);
}
}
}

} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

关于java - 如何从java中的JSONObject获取所有键/子键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49789074/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com