【问题标题】:Jersey - Prevent the mapping of a JavaBean based on QueryParamJersey - 防止基于 QueryParam 的 JavaBean 映射
【发布时间】:2017-03-27 11:03:56
【问题描述】:

我有一个名为 Round 的 Java 类,具有以下构造函数

public Round(){}

public Round(int id, String name, String uri) {
    super();
    this.id = id;
    this.name = name;
    this.uri = uri;
}   

public Round(int id, String name, String uri, List<Stage> stages) {
    this(id, name, uri);
    this.stages = stages;
}

有时我需要在没有阶段的情况下获得有阶段的回合,所以我创建了一个具有两种不同 @GET 方法的 @QueryParam

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Round> getRounds(@QueryParam("withStages") boolean withStages){
    if(withStages){
        return roundService.getRoundsWithStages();
    }else{
        return roundService.getRounds();
    }
}

如果我需要有阶段的回合,我会调用:

/rounds?withStages=true

我得到这样的东西:

[
  {
    "id": 1,
    "name": "First Round",
    "stages": [
      {
        "id": 1,
        "name": "Stage 1",
        "uri": "stage1"
      },
      {
        "id": 2,
        "name": "Stage 2",
        "uri": "stage2"
      }
    ],
    "uri": "firstround"
   }
   //and so on

如果没有阶段我调用:

/rounds?withStages=false

我得到这样的东西:

[
  {
    "id": 1,
    "name": "First Round",
    "stages": [],
    "uri": "firstround"
  },
  {
    "id": 2,
    "name": "Round of 16",
    "stages": [],
    "uri": "roundof16"
  }
  //and so on

您可以看到,当我调用 ?withStages=false 时,我得到了空的阶段数组,但是,我根本不想获得它。我能做什么?

请注意,如果我在 round 类的阶段的 getter 上设置 @XmlTransient,我将无法获取第一个选项 ?withStages=true 中的阶段

我认为一个可能的解决方案是为轮次创建和扩展类,并添加阶段。但是,有没有更好的解决方案?

【问题讨论】:

  • 你是在使用 Jackson 来生成 JSON 吗?
  • 我正在使用 Jersey jax-rs

标签: java web-services rest jersey jax-rs


【解决方案1】:

如果您使用 Jackson 进行序列化,您可以使用 @JsonInclude 注释来指定您何时想要包含某些字段。因此,在您的情况下,您需要在 withStages=false 时隐藏 stages。这可以通过使用@JsonInclude 来完成,如下所示。

public class Round{
     @JsonInclude(value=Include.NON_NULL)
     List<Stage> stages
}

上述规则指定只有当stages 不为空时才应存在阶段。有了上述规则,您必须确保当withStages=falsestages 设置为 null 并且当 withStages=true 时,stages 不为 null。 @JsonInclude 有更多的选项,比如Include.NON_EMPTY,也可以试试。

【讨论】:

  • 我不知道Jersey如何与jackson一起使用,我添加了jersey-json依赖,但是@JsonInclude注解没有出现。
  • 你是如何添加 jersey-json 依赖的?如果使用maven,Json依赖添加为&lt;dependency&lt;groupId&gt;org.glassfish.jersey.media&lt;/groupId&lt;artifactId&gt;jersey-media-json-jackson&lt;/artifactId&gt;&lt;version&gt;your.jersey.version&lt;/version&gt;&lt;/dependency&gt;
  • 谢谢大佬,我解决了。我有一个错误,检查我的答案。 (如果你想删除你的答案,Jersey 可以在不使用 Jackson 的情况下默认省略 Nulls。
【解决方案2】:

问题是因为我有,

public Round {
    ...
    private List<Stage> stages = new ArrayList<>();
    ...
}

我更正为:

public Round {
    ...
    private List<Stage> stages;
    ...
}

而且效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多