FranceMadrid
FranceMadrid

Reputation: 95

How to iterate through json file in Java

In my Json file I have the following field:

"categories": [{
  "name1": "Corporate",
  "parent": {
      "name_parent": "PlanType1"
}
}],

In my Java file I have this code to access that json variable:

PlanType.getnewEntity().getCategories().

The .getCategories() is accessing the "categories" json variable, I just am having trouble iterating through "categories"

In my code I need the logic that if in "categories" if name_parent = "PlanType1" AND name1 = "Corporate" do x. I am just having trouble constructing that if statement by iterating through the json.

Upvotes: 1

Views: 105

Answers (2)

Althaf1467
Althaf1467

Reputation: 291

Try this. I don't actually know how the JSON variable you are getting. But it would work if u cast it into a List of Maps. For example

List<Map<String, Object>> catogoriesList = (List<Map<String, Object>>) PlanType.getnewEntity().getCategories(); 

Then you'll be able to iterate through it like as follows.

for(Map<String, Object> catogory : catogoriesList){
  Map<String, Object> parent = (Map<String, Object>) catogory.get("parent");
  if(catogory.get("name1").toString().equals("Corporate") && parent.get("name_parent").toString().equals("PlanType1")){
    // Do x here
  } 
}

Upvotes: 0

mgeor
mgeor

Reputation: 11

You can iterate like below

 categories.getCategories().forEach(
                category -> {
                    if("Corporate".equals(category.getName1()) &&
                            ("PlanType1".equals(category.getParent().getNameParent()))) {

                        //do the logic
                    }
                }
        );

Upvotes: 1

Related Questions