Niranjan
Niranjan

Reputation: 2921

Best way to represent object views (summary, detail, full etc) in Spring based REST service

I am working on a REST service which uses Spring 4.x. As per a requirement I have to produce several different views out of same object. Sample URIs:

To get full details of a location service: /services/locations/{id}/?q=view:full To get summary of a location service: /services/locations/{id}/?q=view:summary

I have thought of two solutions for such problem: 1. Create different objects for different views. 2. Create same object, but filter out the fields based on some configuration (shown below) location_summary_fields = field1, field2 location_detail_fields = field1, field2, field3

Could someone help me to understand what could be an ideal solution? I am not aware of any standard practice followed for this kind of problems.

Thanks, NN

Upvotes: 0

Views: 416

Answers (2)

Jakub Kubrynski
Jakub Kubrynski

Reputation: 14149

In my opinion the best option is to use separate POJOs for different views. It's a lot easier to document it (for example when you use some automated tools like Swagger). Also you've to remember that your application will change after some time, and then having one common POJO could make troubles - then you'll need to add one field to one service and don't expose it through another.

Upvotes: 1

Krish Srinivasan
Krish Srinivasan

Reputation: 568

See this article on how google gson uses annotations to convert a Java Object representation to a json format : http://www.javacreed.com/gson-annotations-example/

Since you want two different representations for the same object you could roll your own

toJson method as follows :
a) Annotate each field of you model with either @Summary, @Detail or @All
b) Implement a toJson() method that returns a json representation by examining the annotations for the fields and appropriately using them

If you need an XML representation same thing, except you would have a toXML().

Upvotes: 0

Related Questions