For example, you can define a view called Summary and at the same time another called Complete. Le't me show you with a code example.
First of all, you have to define, in your DTO, the required views. In this case we have two views, MessageSummary and MessageEntire.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Message { | |
@JsonView(MessageView.MessageSummary.class) | |
private String content; | |
@JsonView(MessageView.MessageSummary.class) | |
private String author; | |
@JsonView(MessageView.MessageEntire.class) | |
private int likes; | |
public String getContent() { | |
return content; | |
} | |
public void setContent(String content) { | |
this.content = content; | |
} | |
public String getAuthor() { | |
return author; | |
} | |
public void setAuthor(String author) { | |
this.author = author; | |
} | |
public int getLikes() { | |
return likes; | |
} | |
public void setLikes(int likes) { | |
this.likes = likes; | |
} | |
} |
Note that the class used to define your views is an interface which includes other interfaces. Also is important to note, that the MessageEntire view extends from MessageSummary, then all fields marked with MessageSummary are included in the view MessageEntire by inheritance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface MessageView { | |
interface MessageSummary {} | |
interface MessageEntire extends MessageSummary {} | |
} |
Finally, from your REST controller you can choose the required view by the response. For example, in our case, when we construct a new message, it doesn't have sense to return the likes fields because always is equals to zero, otherwise it has sense when the GET method is invoked.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@RestController | |
public class MessageController { | |
@RequestMapping(method = RequestMethod.POST) | |
@JsonView(MessageView.MessageSummary.class) | |
public Message createMessage() { | |
Message m = new Message(); | |
m.setAuthor("John Doe"); | |
m.setContent("I am John Doe"); | |
m.setLikes(0); | |
return m; | |
} | |
@JsonView(MessageView.MessageEntire.class) | |
@RequestMapping(method = RequestMethod.GET) | |
public Message getMessage() { | |
Message m = new Message(); | |
m.setAuthor("John Doe"); | |
m.setContent("I am John Doe"); | |
m.setLikes(23); | |
return m; | |
} | |
} |
Jackson Power!
No comments:
Post a Comment