Java 将 JSONObject 中的所有键转换为 String 数组

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

To get all the keys in JSONObject into String array

javaarraysjson

提问by kishore

I want to create a json object from existing json object. For this i want to get all the keys in JSONObject to a String[] array. Is there any default method to get the keys into a String array. I found there exists a static method heregetNames() but it's not working.

我想从现有的 json 对象创建一个 json 对象。为此,我想将 JSONObject 中的所有键都放到 String[] 数组中。是否有任何默认方法可以将键放入字符串数组中。我发现存在一个静态方法这里)getNames(但它不工作。

I can go over each key using iterator and can construct a keys String array but i want any default method if exists.

我可以使用迭代器遍历每个键,并且可以构造一个键字符串数组,但我想要任何默认方法(如果存在)。

回答by alexey28

To construct JSONObject from other JSONObject you can use constructor that accept JSONObject and array of keys names that should be copied. To do it:

要从其他 JSONObject 构造 JSONObject,您可以使用接受 JSONObject 和应复制的键名数组的构造函数。去做吧:

Iterator keysToCopyIterator = firstJSONObject.keys();
List<String> keysList = new ArrayList<String>();
while(keysToCopyIterator.hasNext()) {
    String key = (String) keysToCopyIterator.next();
    keysList.add(key);
}
String[] kesyArray = keysList.toArray(new String[keysList.size()]);
JSONObject secondJSONObject = new JSONObject(firstJSONObject, );

回答by Iriminage

There is not getNames(), but there is Names()

没有getNames(),但有Names()