我正在尝试从JSON对象中提取密钥。在本例中,JSON对象是通过调用名为SkyRock的社交网站获得的,如下所示:
{
"max_page": 2,
"posts": {
"3111623007": {
"id_post": 3111623007,
"media_align": "float_left",
"tags": [],
"nb_comments": 24
},
"3114564209": {
"id_post": 3114564209,
"media_align": "float_left",
"tags": [],
"nb_comments": 33
},
"3116902311": {
"id_post": 3116902311,
"media_align": "float_left",
"tags": [],
"nb_comments": 29
}
}
}基本上,我希望将所有post_id值存储在ArrayList中。为了做到这一点,我尝试从JSON对象中提取键,并且这样做如下:
JSONObject posts = (JSONObject) jo.get("posts");
ArrayList<String> keys = (ArrayString<String>) posts.keyset();问题是无法找到合适的变量类型来存储从keyset()方法中获得的结果。
我尝试搜索答案,但在大多数情况下, keys ()被用于提取密钥(由于某些原因无法使用,我认为这可能是因为我使用org.json.simple,但不确定)。
有人能帮我找到这个问题的解决方案或检索键值的任何替代方法吗?
谢谢。
发布于 2013-10-05 08:18:17
javadoc说:
public interface JsonObject
extends JsonStructure, Map<String,JsonValue>因此,JSONObject是一个映射,其键为String类型,其值为JSONValue类型。
Map.keySet()说:
Set<K> keySet()
Returns a Set view of the keys contained in this map因此,JSONObject.keySet()返回的是一个Set<String> (这很符合逻辑,因为JSON对象的键是字符串)。
所以你想要的是:
Set<String> keys = posts.keySet();发布于 2013-10-05 08:17:18
posts表示Map of JSONObject,其中key是String
JSONObject mainObject = new JSONObject(jsonString);
JSONObject posts = mainObject.getJSONObject("posts");
Map<String, JSONObject> map = (Map<String,JSONObject>)posts.getMap();
ArrayList<String> list = new ArrayList<String>(map.keySet());
System.out.println(list);输出:
[3116902311, 3114564209, 3111623007]发布于 2016-12-14 14:45:06
这个对我有用
O是一个JSONObject ->导入org.json.simple.JSONObject;
Set<?> s = o.keySet();
Iterator<?> i = s.iterator();
do{
String k = i.next().toString();
System.out.println(k);
}while(i.hasNext());https://stackoverflow.com/questions/19195492
复制相似问题