jbrown
jbrown

Reputation: 7996

How to work with multiple 'views' of the same domain model?

I'm using Jackson to parse JSON for my android app. I also intend to use it in my REST server too, so I'll be sharing my models between client and server.

I've created a POJO to model a domain object "Friend". When the client gets https://www.myserver.com/api/1/friend/1234 I want to return the serialised Friend with ID 1234, perhaps with one or 2 fields missing.

However, when a client gets https://www.myserver.com/api/1/friend/ I want to return all friend objects, but with less data that might be more appropriate to search results (e.g. just first name, last name and profile image, but excluding their list of friends, date of birth, etc.).

What pattern should I follow here so that I can represent the same underlying model in different ways depending on how it'll be accessed?

Upvotes: 1

Views: 168

Answers (2)

Bart
Bart

Reputation: 17371

Inheritance can be an option in conjunction with @JsonIgnoreProperties.

You can have a class Friend and extend it to restrict what properties are to be serialized.

@JsonIgnoreProperties({ "friends", "dateOfBirth" })
class RestrictedFriend extends Friend {

}

Upvotes: 1

Wand Maker
Wand Maker

Reputation: 18762

See if you want to use Inheritance. Have a base class with fields that you want to share with everyone, and a sub-class which has more restricted data. Have two JSON APIs, one for public info, and one for public+secure info, and serialize the base class or sub-class object based on which API was called.

Upvotes: 0

Related Questions