1

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?

1
  • It Looks perfectly fine to me. You are right about extra coding to create more subsets but I think it is worth it because you can fine tune them for views and they have low impact if underlying model is changed. Commented Apr 5, 2013 at 21:57

1 Answer 1

1

Look at Jackson's JSON Views and Filters

http://wiki.fasterxml.com/JacksonJsonViews

http://wiki.fasterxml.com/JacksonFeatureJsonFilter

Sign up to request clarification or add additional context in comments.

1 Comment

The JSONFilter sounds like the solution. I'll try it out, but maybe you can give me an additional hint how to combine this with the Controller to achieve my goal, because currently I don't really care about Jackson, it's all done by Spring...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.