无论名称

时间:2015-11-04 20:07:00

标签: java android jsonobject

我想知道是否有办法在不知道其名称的情况下获取JSONObject的第一个子节点的值:

我有一个名为this_guy

的节点的JSON
{"this_guy": {"some_name_i_wont_know":"the value i care about"}}

使用JSONObject,我如何获得"我关心的价值,"如果我不知道孩子的名字,我会干净利落地。我所知道的只是" this_guy",任何人?

3 个答案:

答案 0 :(得分:13)

使用JSONObject.keys() 返回此对象中的字符串名称的迭代器。然后使用这些键来检索值。

仅获取第一个值:

$scope.angularFunction

答案 1 :(得分:0)

Object obj = parser.parse(new FileReader("path2JsonFIle"));

JSONObject jsonObject = (JSONObject) obj;

试试这个迭代器

JSONObject jsonObj = (JSONObject)jsonObject.get("this_guy");

for (Object key : jsonObj.keySet()) {
        //based on you key types
        String keyStr = (String)key;
        Object keyvalue = jsonObj.get(keyStr);

        /*check here for the appropriate value and do whatever you want*/
        //Print key and value
        System.out.println("key: "+ keyStr + " value: " + keyvalue);

    }

一旦得到适当的值,就要摆脱循环。例如,你说你需要的只是内部地图中的第一个值。所以试试像

这样的东西
int count = 0;

String valuINeed="";
for (Object key : jsonObj.keySet()) {
            //based on you key types
            String keyStr = (String)key;
            Object keyvalue = jsonObj.get(keyStr);

            valueINeed = (String)keyvalue;
            count++;

            /*check here for the appropriate value and do whatever you want*/
            //Print key and value
            System.out.println("key: "+ keyStr + " value: " + keyvalue);

            if(count==1)
                break;

        }

          System.out.println(valueINeed);

答案 2 :(得分:0)

如果您只在乎值而不在乎键,则可以直接使用:

Object myValue = fromJson.toMap().values().iterator().next();
相关问题