Fetch data from a nested JsonArray in JsonObject | Community
Skip to main content
Level 4
July 21, 2023
Solved

Fetch data from a nested JsonArray in JsonObject

  • July 21, 2023
  • 3 replies
  • 1750 views

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"

        }]

    }

}

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by imshailesh

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

3 replies

nitesh_kumar-1
Adobe Employee
Adobe Employee
July 21, 2023

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

Sady_Rifat
Community Advisor
Community Advisor
July 21, 2023

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

imshaileshAccepted solution
Level 2
July 21, 2023

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