使用keySet()从JSONObject中提取键 [英] Extracting Keys from a JSONObject using keySet()

查看:783
本文介绍了使用keySet()从JSONObject中提取键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON对象中提取密钥。在这种情况下,JSON对象是通过对名为 SkyRock 的社交网站进行API调用获得的,如下所示:

I'm trying to extract the keys from a JSON Object. The JSON object, in this case, is obtained by making an API call to a social networking site called SkyRock and looks like this :

{
  "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对象中提取,并按如下方式执行此操作:

I basically want to store all the post_id values in an ArrayList. In order to do this, am trying to extract the keys from the JSON object and am doing this as follows:

JSONObject posts = (JSONObject) jo.get("posts");
ArrayList<String> keys = (ArrayString<String>) posts.keyset();

问题是无法找到合适的变量类型,我可以在其中存储获得的结果来自 keyset()方法。

The problem is that am not able to find a suitable variable type in which I can store the result obtained from the keyset() method.

我尝试搜索答案,但在大多数情况下,键()用于提取密钥(由于某种原因我无法使用它,我认为这可能是因为我使用的是org.json.simple,但我不确定)。

I tried searching for the answers, but in most of the cases, keys() is being used to extract the keys (which am not able to use for some reason and I think it's maybe because am using org.json.simple, but am not sure).

任何人都可以帮我在这里找到问题的解决方案或任何替代方法来检索Key值吗?

Can anyone please help me out here to find a solution to the problem or any alternate method to retrieve the Key values?

谢谢。

推荐答案

javadoc 说:

public interface JsonObject
extends JsonStructure, Map<String,JsonValue>

因此,JSONObject是一个Map,其键的类型为 String ,其值为 JSONValue

So, a JSONObject is a Map whose keys are of type String, and whose values are of type JSONValue.

并且 javadoc 地图< K,V> ; .keySet() 说:

Set<K> keySet()

Returns a Set view of the keys contained in this map

那么, JSONObject.keySet()返回的是 Set< String> (这是非常合乎逻辑的,因为键JSON对象是字符串)。所以你想要:

So, what JSONObject.keySet() returns is a Set<String> (which is quite logical, since keys of JSON objects are strings). So you want:

Set<String> keys = posts.keyset();

这篇关于使用keySet()从JSONObject中提取键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆