I have a json file with users, each users has email
and password
and corresponding POJO exist to deserialize them.
I'm using both jackson
and JSON.simple
.
However, I want to add users at will, and create a method to find them by their description, let's say this is my json:
{
"user1": {
"email": "user1@user.com",
"password": "qwe123",
},
"user2": {
"email": "user2@user.com",
"password": "abc123",
},
...
"userX": {
"email": "userX@user.com",
"password": "omg123",
}
}
This is my POJO:
public record User(String email, String password) {}
I dont want to create superPOJO and add each user as I create them.
I would like to create method that would read my json, and returned the User
object based on String input.
For now I created users in array and get them using their index, but now situation requires giving users "nicknames" and getting them by their nickname.
Now I am keeping user like this:
[
{
"email": "xxx@xxx.com",
"password": "xxx111",
},
{
"email": "yyy@yyy.com",
"password": "yyy222",
}
]
This is my current method:
public User getUser(int index) throws IOException {
return Parser.deserializeJson(getUserFile(), User[].class)[index];
}
where Parser#deserializeJson()
is:
public <T> T deserializeJson(String fileName, Class<T> clazz) throws IOException {
return new ObjectMapper().readValue(Utils.reader(fileName), clazz);
}
And Utils.reader
just brings file from the classpath.
I would like a method like this:
public User getUser(String nickname) throws IOException {
return Parser.deserializeJson(getUserFile(), User.class);
}
and when calling this method with parameter nickname
of user2
I'd get User
object with fields: email user2@user.com
and password abc123