简体   繁体   English

无论名称如何,JSONObject都获取第一个节点的值

[英]JSONObject get value of first node regardless of name

I am wondering if there is a way to get the value of the first child of a JSONObject without knowing its name: 我想知道是否有办法在不知道其名称的情况下获取JSONObject的第一个子节点的值:

I have some JSON coming in with a node called, this_guy 我有一些JSON进来了一个叫做this_guy的节点

{"this_guy": {"some_name_i_wont_know":"the value i care about"}}

Using JSONObject, how can I get "the value i care about," cleanly if I don't know the name of the child. 使用JSONObject,如果我不知道孩子的名字,怎么能干净利落地得到“我关心的价值”。 All I know is "this_guy", anyone? 我所知道的只是“this_guy”,有人吗?

Use JSONObject.keys() which returns an iterator of the String names in this object . 使用JSONObject.keys() 返回此对象中String名称的迭代器 then use these keys to retrieve values. 然后使用这些键来检索值。

To get only first value: 仅获得第一个值:

 Iterator<String> keys = jsonObject.keys();
 // get some_name_i_wont_know in str_Name
 String str_Name=keys.next(); 
 // get the value i care about
 String value = json.optString(str_Name);
Object obj = parser.parse(new FileReader("path2JsonFIle"));

JSONObject jsonObject = (JSONObject) obj;

try this iterator 试试这个迭代器

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);

    }

once you get the appropriate value, just break out of the loop. 一旦你得到了适当的值,就摆脱循环。 for example you said that all you need is the first value in the inner map. 例如,你说你需要的只是内部地图中的第一个值。 so try womething like 所以试试像

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);

如果您只关心价值而不关心关键,您可以直接使用:

Object myValue = fromJson.toMap().values().iterator().next();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM