如果Java的构造函数中不存在Json属性,则忽略它

时间:2018-08-17 08:38:49

标签: java json

我有一堂课,如下所示:-

@Getter
@Setter
@NoArgsConstructor
public class Response extends ResponseMessage {

    @JsonProperty("ResponseDto")
    private myDTo myDto;

    @JsonProperty("revId")
    private Long revisionId;

    @JsonProperty("modelId")
    private Long model;

    public Response(HttpStatus status, String message) {
        super(status, message);
    }

    public Response(HttpStatus status, String message, Long revisionId) {
        super(status, message);
        this.revisionId = revisionId;
    }

    public Response(HttpStatus status, String message, Long revisionId, Long modelId) {
        super(status, message);
        this.revisionId = revisionId;
        this.model = modelId;
    }

    public Response(HttpStatus status, String message, myDTo myDto) {
        super(status, message);
        this.myDto = myDto;
    }
}

现在,当我返回Response类作为响应时,如下所示:-

return new Response(HttpStatus.OK,"done",123);

它返回响应json为:-

{
"revId":123,
"status":"OK",
"modelId":null,
"message":"done"
}

,但要响应取决于所调用的构造函数。在这种情况下应该是:-

{
"revId":123,
"status":"OK",
"message":"done"
}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您应该使用@JsonInclude(Include.NON_NULL)忽略空字段。