Expand my Community achievements bar.

Join us in celebrating the outstanding achievement of our AEM Community Member of the Year!
SOLVED

Fetch data from a nested JsonArray in JsonObject

Avatar

Level 5

I need to get values of 'division' from this JsonObject in AEM. How can I get that?

{

 "orgUnit": {

    "active": true,

    "category": [{

        "l": "08",

        "division": "03",

        "isDefault": false,

        "sales": "ID01"

        }]

    }

}

1 Accepted Solution

Avatar

Correct answer by
Level 3

Hi @goyalkritika !

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Test {
    public static void main(String[] args)  {
        String jsonString = "{\"orgUnit\":{\"active\":true,\"category\":[{\"l\":\"08\",\"division\":\"03\",\"isDefault\":false,\"sales\":\"ID01\"}]}}";
        JsonObject json = new Gson().fromJson(jsonString, JsonObject.class);
        JsonArray jsonArray =  json.getAsJsonObject("orgUnit").getAsJsonArray("category");
        System.out.println(jsonArray.get(0).getAsJsonObject().get("division"));
    }
}

 

You can use the above as reference.

 

Regards,

Shailesh

View solution in original post

3 Replies

Avatar

Employee Advisor

Hi @goyalkritika ,

 

Have you tried to use GSON Api? you need to iterate through Json Array (category) and fetch the value(division) from each Jsonobject, Assuming you want to fetch it at the backend using Java.

https://javadoc.io/doc/com.google.code.gson/gson/latest/com.google.gson/module-summary.html 

 

Hope this helps.

 

Regards,

Nitesh

Avatar

Community Advisor

Hello @goyalkritika ,

You can try the following code,

    Gson gson = new Gson();

    // If you have the Json in string, jsonString = "{ "orgUnit" .....}"
    // If you already have jsonObject just skip this line
    JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class);

    JsonObject orgUnit = jsonObject.getAsJsonObject("orgUnit");
    JsonArray categoryArray = orgUnit.getAsJsonArray("category");
    if (categoryArray.size() > 0) {
        JsonObject categoryObject = categoryArray.get(0).getAsJsonObject();
        String divisionValue = categoryObject.get("division").getAsString();
    }

Or you can cast to in your Pojo class if you have any

Avatar

Correct answer by
Level 3

Hi @goyalkritika !

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Test {
    public static void main(String[] args)  {
        String jsonString = "{\"orgUnit\":{\"active\":true,\"category\":[{\"l\":\"08\",\"division\":\"03\",\"isDefault\":false,\"sales\":\"ID01\"}]}}";
        JsonObject json = new Gson().fromJson(jsonString, JsonObject.class);
        JsonArray jsonArray =  json.getAsJsonObject("orgUnit").getAsJsonArray("category");
        System.out.println(jsonArray.get(0).getAsJsonObject().get("division"));
    }
}

 

You can use the above as reference.

 

Regards,

Shailesh