Pushpak :
I have a JSON array like this:
[{
"name": "com",
"children": [
{
"name": "project",
"children": [
{
"name": "server"
},
{
"name": "client",
"children": [
{
"name": "util"
}
]
}
]
}
]
}]
And I need all the names from all the JSON objects. Is there any way to get this done in java?
I want a recursive function.
My expected result is like :
[
{name:"com"},
{"name":"project"},
{"name":"server"},
{"name":"client"},
{"name":"util"}]
noiaverbale :
This is a simple recursive function to get all names
properties from your json array:
public static Collection<String> getAllNames(JSONArray jsonArray, List<String> names) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
names.add(object.getString("name"));
if (object.has("children")) {
JSONArray children = object.getJSONArray("children");
getAllNames(children, names);
}
}
return names;
}
This will provide you a list of names that you can use to construct a new json array. A possible way is this:
public static JSONArray getJsonArraysOfNames(List<String> names) {
JSONArray jsonArray = new JSONArray();
for (String name : names) {
JSONObject object = new JSONObject();
object.put("name", name);
jsonArray.put(object);
}
return jsonArray;
}
UPDATE
If you prefer an all-in-one solution then you can go with this approach:
public static JSONArray getNames(JSONArray inputArray, JSONArray outputArray) {
for (int i = 0; i < inputArray.length(); i++) {
JSONObject inputObject = inputArray.getJSONObject(i);
JSONObject outputObject = new JSONObject();
outputObject.put("name", inputObject.getString("name"));
outputArray.put(outputObject);
if (inputObject.has("children")) {
JSONArray children = inputObject.getJSONArray("children");
getNames(children, outputArray);
}
}
return outputArray;
}