Search code examples
javajsonpojo

Creating POJO objects from JSON array String


I have a JSON array string like below.

"[
  {
    "id" : "123",
    "name":"John Doe",
    "Address":"53/A"
    
   },
   {
    "id" : "1234",
    "name":"John Doe1",
    "Address":"53/AB"
    
   }
  
]"

I have a POJO class which maps with the inner JSON objects like below.

class User {
  String id;
  String name;
  String Address;
 //Getters & Setters
}

I want to create POJO objects from the above String and create a User ArrayList. How can I achieve this ? (using a library like Gson is fine). Thank you.


Solution

  • ArrayList<LinkedTreeMap> list = gson.fromJson(json, ArrayList.class);
    List<User> users= list.stream()
                      .map(s -> gson.fromJson(gson.toJson(s), User.class))
                      .collect(Collectors.toList());