【问题标题】:JAVA - Using same POJO but with less fields (without jackson)JAVA - 使用相同的 POJO 但字段较少(没有杰克逊)
【发布时间】:2021-12-13 20:20:07
【问题描述】:

我有一个现有端点使用的 POJO,该端点以 POJO 中存在的所有字段进行响应。
但是我正在创建一个新的 enpoint,它应该只响应同一个 POJO 的一些字段。
我想避免复制同一个POJO文件并删除我不需要的参数,有没有办法做到这一点?

这是 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;

假设我只需要在端点 2 中显示“Id”,但在端点 1 中显示 id 和 queueId。 我和春天一起工作。 谢谢!

【问题讨论】:

  • 参数?你有字段吗?您是在谈论将对象序列化为 JSON 吗?为什么没有杰克逊——那你用什么?
  • 我们还需要看看这个类是如何被你的应用返回的。你用什么框架,你根本不说?
  • 是的,我的意思是字段,没有杰克逊,因为我需要一个端点来响应所有字段,而另一个端点只响应一些字段。
  • 在我的应用中使用 spring
  • 但是您使用的是 Jackson 吗?因为杰克逊可以在这方面提供帮助。

标签: java object pojo


【解决方案1】:

使用 Jackson,您可以利用 JSON 视图。首先是按如下方式创建视图:

public class Views {
    public static class ViewEndpoint2 { // The name can be whatever you want
    }

    public static class ViewEndpoint1 extends ViewEndpoint2 {
    }
}

然后你需要用@JsonView注释你的POJO中的属性,这样你就可以告诉Jackson这些属性应该在哪些视图中可见:

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;
}

最后,你需要用对应的视图来注解端点:

@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) 基本上是指AgentChatStatusAgentChat@JsonView(Views.ViewEndpoint2.class) 中的所有属性,仅表示其中的一部分(带有@JsonView(Views.ViewEndpoint2.class) 注释的属性)。

您可以在https://www.baeldung.com/jackson-json-view-annotation 阅读更多相关信息。

【讨论】:

  • 这个有什么需要,谢谢!我将在今天实现这一点,并在此处反馈反馈。
  • 让我知道它是否有效;)
  • 是的,您只需对这些类应用相同的逻辑即可。如果您分享它们并告诉我们您希望在第二个端点中排除哪些属性,我可以更新我的答案。
  • 完成,请查看我的更新答案;)
  • 优秀,正如我们所说的,我会评论反馈,这正是我所需要的,谢谢
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
相关资源
最近更新 更多