skip to Main Content

Consider this:

List<String> users = repo.findAllById(id):

And this:

Public Users{
int id;
string name;
}

The list of users contain a json of users with id and names.
My question is, how do I convert the list of strings(json) into a list of users. Thanks everyone.

Eg. of list:

[user1:
  {
    “id”: “24”,
    “name”: “name”
   }
user2:
  {
    “id”: “24”,
    “name”: “name”
   }
]

2

Answers


  1. Is there a reason why you want the list to contain strings, and not a User object? If not, you could try this:

    List<User> users = repo.findAllById(id);
    return users;
    
    Login or Signup to reply.
  2. I am not quite sure how is your List<String> users data structure looks like?
    You can do the convert using as below.

    https://mvnrepository.com/artifact/org.json/json/20220924
    // JSONObject dependency
    
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20180130</version>
    </dependency>
    
    
    
    List<String> strUsers = repo.findAllById(id):
    
    List<User> users = strUsers.stream().map(m => {
      JSONObject obj = new JSONObject(m);
      return new User(obj.getInt("id"), obj.getString("name"));
    }).collect(Collectors.toList());
    

    If you would like to have an accuracy answers
    please provide more detail such

    • how you select sql ?
    • you use JDBC or JPA ?
    • how is the List users data structure?
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search