I have a POJO used by an existing endpoint, this endpoint responds with all fields present in the POJO.
But I'm creating a new enpoint which should respond only some of the fields of the same POJO.
I want to avoid copying the same POJO file and deleting the parameters I don't need, is there a way to do this?
This is the POJO:
public class AgentChatStatus {
private UUID activeChat;
private List<AgentChat> chatRequests; //Object with less params on new endpoint
private List<AgentChat> chatsOnHold; //Object with less params on new endpoint
private Collection<Agent> agents;
private int totalChatRequests;
private int totalChatsOnHold;
private Preferences.AgentConsoleConfig config;
// ...
}
public class AgentChat implements Payload {
private UUID id;
private String queueId;
Lets say I only need to show "Id" in endpoint 2 but id and queueId in endpoint1. I work with spring btw. Thanks!
CodePudding user response:
With Jackson you can take advantage of JSON Views. The first thing is to create the Views as follows:
public class Views {
public static class ViewEndpoint2 { // The name can be whatever you want
}
public static class ViewEndpoint1 extends ViewEndpoint2 {
}
}
Then you need to annotate the properties in your POJO with @JsonView
so that you tell Jackson in which views such properties should be visible:
public class AgentChatStatus {
@JsonView(Views.ViewEndpoint2.class)
private UUID activeChat;
@JsonView(Views.ViewEndpoint2.class)
private List<AgentChat> chatRequests;
@JsonView(Views.ViewEndpoint2.class)
private List<AgentChat> chatsOnHold;
@JsonView(Views.ViewEndpoint2.class)
private Collection<Agent> agents;
@JsonView(Views.ViewEndpoint2.class)
private int totalChatRequests;
@JsonView(Views.ViewEndpoint2.class)
private int totalChatsOnHold;
@JsonView(Views.ViewEndpoint2.class)
private Preferences.AgentConsoleConfig config;
}
public class AgentChat implements Payload {
@JsonView(Views.ViewEndpoint2.class)
private UUID id;
@JsonView(Views.ViewEndpoint1.class)
private String queueId;
}
Finally, you need to annotate the endpoints with the corresponding view:
@JsonView(Views.ViewEndpoint1.class)
@RequestMapping("your-old-enpoint")
public void yourOldEndpoint() {
(...)
}
@JsonView(Views.ViewEndpoint2.class)
@RequestMapping("your-new-enpoint")
public void yourNewEndpoint() {
(...)
}
@JsonView(Views.ViewEndpoint1.class)
basically means all properties in AgentChatStatus
and AgentChat
and @JsonView(Views.ViewEndpoint2.class)
means only some of them (the ones annotated with @JsonView(Views.ViewEndpoint2.class)
).
You can read more about this at https://www.baeldung.com/jackson-json-view-annotation.