我有一个名为 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 时,我得到空的阶段数组,但是,我根本不想获得它。我能做什么?
请注意,如果我在回合类中阶段的获取器上设置@XmlTransient,我将无法在第一个选项中获得阶段 ?withStages=true
我认为一个可能的解决方案是为圆形创建和扩展类,并向其添加阶段。但是,有没有更好的解决方案?
如果使用 Jackson 进行序列化,则可以使用@JsonInclude
注释来指定何时要包含某些字段。所以在您的情况下,您需要在withStages=false
时隐藏stages
.这可以通过使用如下所示的@JsonInclude
来完成。
public class Round{
@JsonInclude(value=Include.NON_NULL)
List<Stage> stages
}
上述规则指定仅当 stages
不为 null 时才应存在阶段。有了上述规则,您必须确保当 withStages=false
、stages
设置为 null 时,当 withStages=true 时,stages 不为 null。@JsonInclude
中还有更多选项,例如Include.NON_EMPTY
也可以尝试。
问题是因为我有,
public Round {
...
private List<Stage> stages = new ArrayList<>();
...
}
我将其更正为:
public Round {
...
private List<Stage> stages;
...
}
而且它工作正常。