java 我可以从 JSONObject 获取价值而不提及其名称吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10459636/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:07:43  来源:igfitidea点击:

Can I get value from JSONObject without mention its name?

javajsonorg.json

提问by panji

My JSONObject:

我的 JSONObject:

{MyJSON:[{"id":"1","name":"panji","price":"100"}]}

I do this to get value of id:

我这样做是为了获得 id 的值:

menuitemArray.getJSONObject(i).getString("id");

Can I get the value of id, name or price, without mentioning its name, may be like index or another method?

我可以获取id,name或price的值,不提它的名字,可能是index或其他方法吗?

回答by Paul Bellora

You can call names()on a JSONObjectto get a JSONArrayof the names of its elements - this would let you do logic on them or retrieve their corresponding values dynamically.

您可以调用names()aJSONObject来获取JSONArray其元素的名称 - 这将允许您对它们进行逻辑处理或动态检索它们的相应值。

回答by gkamal

You can get all the attributes of a JSONObject like this

您可以像这样获取 JSONObject 的所有属性

for(Iteraor key=jsonObject.keys();itr.hasNext();) {
   jsonObject.get(key.next());
}

回答by Ziad Alzarka

JSONObject obj = new JSONObject(json);
for(Iterator<String> keys=obj.keys();keys.hasNext();) {
    obj.get(keys.next());
}