-8

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 Answers2

0

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;
charbs29
  • 69
  • 7
  • The problem is that I already have this method name in my repository and jpa repos don’t seem to allow method overloading unless you know of some other ways. Thanks @charbs29 – clement mensah Dec 06 '22 at 07:32
  • If you want a list of JSON, there are plenty of answers through stack overflow that can help you convert your models to JSON. – charbs29 Dec 07 '22 at 16:47
0

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?
Spring
  • 831
  • 1
  • 12
  • 42