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
Given your input json is an object (map) of User-like objects:
{
"user1": {
"email": "user1@user.com",
"password": "qwe123",
},
"user2": {
"email": "user2@user.com",
"password": "abc123",
},
...
"userX": {
"email": "userX@user.com",
"password": "omg123",
}
}
then you should be able to deserialize it into a (Hash)Map of Users:
public <T> Map<String, Class<T>> deserializeJson(String fileName) throws IOException {
return new ObjectMapper().readValue(Utils.reader(fileName), new TypeReference<HashMap<String, Class<T>>>(){});
}
and then use it like so:
public User getPredefinedUser(String nickname) throws IOException {
return Parser.deserializeJson(getUserFile(), User.class).get(nickname);
}
(Although you probably want to parse once and store that somewhere, not parse every time).
Thanks for the compile check and fix by hetacz. Had the templates wrong, and an unnecessary (for this case) class variable