Java Json 对象 - 获取键和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23826520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Json Object - Getting the Key and the Value
提问by algo1
I am a newbie to JSON . So If this is a very basic doubt don't scold me . I have a JSON Object Reference and I want to get the Key(Object has only one Key Value Pair) . How do I get it in Java ?
我是 JSON 的新手。所以如果这是一个非常基本的疑问,请不要骂我。我有一个 JSON 对象引用,我想获取 Key(Object has only one Key Value Pair) 。我如何在 Java 中获取它?
采纳答案by Unnati
You can use jsonObject.keys()
for getting all keys. Then you may iterate over keys to get the first key out of them like :
您可以jsonObject.keys()
用于获取所有密钥。然后您可以迭代键以从中获取第一个键,例如:
Iterator<String> keys = jsonObject.keys();
if( keys.hasNext() ){
String key = (String)keys.next(); // First key in your json object
}
回答by Apoorv
json.keys()
will give all the keys in your JSONObject
where json
is an object of JSONObject
json.keys()
将给出你JSONObject
wherejson
中的所有键,是一个对象JSONObject
回答by Baker
Recursively search for a key, and if found, return its value
递归搜索一个键,如果找到,返回它的值
String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
Iterator<?> keys = jObj.keys();
String key = "";
while (keys.hasNext() && !key.equalsIgnoreCase(findKey)) {
key = (String) keys.next();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
if (jObj.get(key) instanceof JSONObject) {
return recurseKeys((JSONObject)jObj.get(key), findKey);
}
}
return "";
}
Usage:
用法:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");