Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To get all the keys in JSONObject into String array

Tags:

java

json

arrays

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.

like image 801
kishore Avatar asked Dec 06 '13 08:12

kishore


People also ask

Can a JSON object be an array?

JSON can be either an array or an object.

Can JSON keys be arrays?

A JSON value can be an object, array, number, string, true, false, or null, and JSON structure can be nested up to any level.

How do I get keys from JSONArray?

and how to get value of corresponding keys and then randomize the values of keys each time. jsonObject. get(key) will give you the value of a particular key. Randomizing depends on what/how you want to randomize.

How do I get the value of a JSON object?

getJsonObject() Method It is used to get the (JsonObject)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the object of the associated mapping for the parse's parameter. It returns null if the object has no mapping for the parameter.


1 Answers

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, );
like image 93
alexey28 Avatar answered Sep 23 '22 20:09

alexey28