将 JSONObject 中的所有键转换为 String 数组 [英] To get all the keys in JSONObject into String array

查看:167
本文介绍了将 JSONObject 中的所有键转换为 String 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 here getNames() but it's not working.

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

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

推荐答案

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

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:

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

这篇关于将 JSONObject 中的所有键转换为 String 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆