Fetch data from a nested JsonArray in JsonObject | Adobe Higher Education
Skip to main content
Level 4
July 21, 2023
Respondido

Fetch data from a nested JsonArray in JsonObject

  • July 21, 2023
  • 3 respostas
  • 1805 Visualizações

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"

        }]

    }

}

Este tópico foi fechado para respostas.
Melhor resposta por 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 Respostas

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

imshaileshResposta
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