The web service tier of our application creates JSON from the internal business objects.
Some properties are completely hidden, that was easy
public class User {
@JsonIgnore
public String getHash() {
return hash;
}
// lot more getters and setters
}
Because of performance reasons I thought to not always deliver the full user (any other) object.
So when using the /rest/users it should only deliver a subset of properties for every user.
When using /rest/user/{id} it will deliver all
Also this can be achieved more or less easy by wrapping the user object into different models, that have less getters then the user.
public class PublicUserModel {
private User user;
public PublicUserModel(User user) {
this.user = user;
}
public String getFirstname() {
return user.getFirstname();
}
public String getLastname() {
return user.getLastname();
}
}
But this is a lot of coding and not very flexible for different views.
Ideally there is a way to tell the @Controller what properties should be available. All other code is a lot of work.
@Controller
public class MainController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping(value = "/users/{id}")
public MyUserModel getUser(@PathVariable String id) {
User user = userService.getUser(id);
if (user != null) {
return new MyUserModel(user);
}
return null;
}
@ResponseBody
@RequestMapping(value = "/users")
public Collection<PublicUserModel> getUsers() {
Collection<User> users = userService.getAllUsers();
Collection<PublicUserModel> publicUsers = new ArrayList<>();
for (User user : users) {
publicUsers.add(new PublicUserModel(user));
}
return publicUsers;
}
}
Any ideas for a generic Model?