-3

I have a string of the form

String str = "[
             {"id": 1, "name":"Abc", "Eligible": "yes"},
             {"id": 2, "name":"Def", "Eligible": "no"},
             {"id": 3, "name":"Ghi", "Eligible": "yes"},
             {"id": 4, "name":"Jkl", "Eligible": "no"}
             ]";

I want to parse each JSON from the list. Thank you.

Utkarsh
  • 137
  • 9

2 Answers2

0

Hi I can provide very crude answer to you question.

Add this dependecy in pom.xml

    <dependencies>
        ...
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>
      ...
    </dependencies>

Jave Code:

 public static void main(String... args) {
       String str = "[ {\"id\": 1, \"name\":\"Abc\", \"Eligible\": \"yes\"}, {\"id\": 2, \"name\":\"Def\", \"Eligible\": \"no\"}, {\"id\": 3, \"name\":\"Ghi\", \"Eligible\": \"yes\"}, {\"id\": 4, \"name\":\"Jkl\", \"Eligible\": \"no\"}]";

        Gson gson = new Gson();
        Object o = gson.fromJson(str, Object.class);
        String name = ((LinkedTreeMap) ((ArrayList) o).get(0)).get("name").toString();
        System.out.println("name is "+ name);
}

Output:

name is Abc
0

You can parse list from the input json string, there are multiple ways and different libraries you can use to parse.

Maven dependency :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>
 String str = "[{\"id\":1,\"name\":\"Abc\",\"Eligible\":\"yes\"},{\"id\":2,\"name\":\"Def\",\"Eligible\":\"no\"},{\"id\":3,\"name\":\"Ghi\",\"Eligible\":\"yes\"},{\"id\":4,\"name\":\"Jkl\",\"Eligible\":\"no\"}]";

     JSONArray jsonArray = new JSONArray(str);

        for (int i = 0; i < jsonArray.length(); i++) {
            int id = ((JSONObject)jsonArray.get(i)).getInt("id");
            String name = ((JSONObject)jsonArray.get(i)).getString("name");
            String eligible = ((JSONObject)jsonArray.get(i)).getString("Eligible");
             
        }

Maven dependency

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.7</version>
</dependency>

Create a class for the object that corresponds to the object in the input list.

In your case it would be:

class Item{
        int id;
        String name;
        String Eligible;
        //getter setter
    }

String str = "[{\"id\":1,\"name\":\"Abc\",\"Eligible\":\"yes\"},{\"id\":2,\"name\":\"Def\",\"Eligible\":\"no\"},{\"id\":3,\"name\":\"Ghi\",\"Eligible\":\"yes\"},{\"id\":4,\"name\":\"Jkl\",\"Eligible\":\"no\"}]";
Type listType = new TypeToken<ArrayList<Item>>(){}.getType();
List<Item> items = new Gson().fromJson(str, listType);
for (Item item: items){
   //access the item
}

tsukyonomi06
  • 514
  • 1
  • 6
  • 19