I am using a JSON map to save objects (e.g. users) whose ids are the keys of the map but the object (user) itself also contains the id.
JSON
{
"john":{
"username":"john",
"age":30
},
"bob":{
"username":"bob",
"age":40
},
"chris":{
"username":"chris",
"age":50
}
}
Class
class user {
String username;
Integer age;
getUsername() {
return username;
}
}
I want to use the map to retrieve the objects easily but at the same time I don't want to have ids as keys in the map and as attributes of the object. What is the cleanest solution for this?
I can think of the following solutions:
- Don't use map but list. But then accessing the elements will need an iteration over the list and I can't use simple
get(K key)
methods. - Don't save username in object But then
getUsername()
will need to know where it was saved in the map which will imho be really bad coupling. - Use enums for usernames But then users can not be dynamically read from JSON.