Introduction
There are scenarios where we have a DTO or a model class that contains a collection of properties and there might be some endpoints that require a subset of them and some other endpoint that might need all of them.
Example: Consider a scenario where we need a list of Categories in a dropdown and we have an API that gets all the categories from the static masterdata and need to send to the UI in response to an API call.
Problem Statement
We might choose to use a `Map` data type so that we send out the key-value pairs to the database or to choose to build a custom DTO with only the Id, name of the categories.
In a longer run, if we opt to use multiple DTO in the source, sooner there will be a very large collection of DTO classes that represent subset of a static data.
Solution
Rather than ending up with a large number of such DTO classes, we can use a JSON View. This helps us have a single class and control which fields are part of which view.
Example: We can have a dropdown view in categories that will have an Id,Name alone. Similarly, there might be a grid view which might need some other subset of properties, which can be referred through a view.
This helps us a lot because we no longer have to worry about the multiple DTO, but we can be able to view in a single class definition, which properties are used by which parts of the application.
Below given is a sample application that illustrates the above concepts.
The Categories Class
public class Categories implements Serializable {
@JsonView({CategoryViews.CategoryCollectionView.class, CategoryViews.CategoryExecutionView.class})
private Long id = null;
@NotNull
@JsonView({CategoryViews.CategoryCollectionView.class, CategoryViews.CategoryExecutionView.class})
private String name = null;
@JsonView(CategoryViews.CategoryCollectionView.class)
private Long createdBy = null;
@JsonView(CategoryViews.CategoryCollectionView.class)
private Date createdOn = new Date();
@JsonView(CategoryViews.CategoryExecutionView.class)
private boolean executable = false;
}
The CategoryView are defined like below
public interface CategoryViews{
interface CategoryCollectionView{
}
interface CategoryExecutionView{}}
The usage in an API controller
@GetMapping(value = "categories/forExecution", produces = {APPLICATION_JSON_VALUE})
@JsonView(CategoryViews.CategoryExecutionView.class)
public ResponseEntity<List<Categories>> getFilterExecutableCategories(... ) { ... }
Comments
Post a Comment