【问题标题】:Stop the (pojo) serialization if one of the required fields is null如果必填字段之一为空,则停止 (pojo) 序列化
【发布时间】:2017-07-20 06:44:44
【问题描述】:

考虑以下 POJO:

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonInclude(content=Include.NON_NULL)
public class User {
    @JsonProperty(required=true)
    private String username;
    private String dob;
    private String email;
    //        ... (getters and setters)

}

考虑上述 pojo 的以下示例 JSON:

{
    "username": "foo",
    "email": "foo@bar.com",
    "dob": "12/21/1994"
}

如果我将一个字段指定为null,它将在序列化发生时被忽略。

提出我的问题,当必填字段为 null 时,有没有办法停止序列化(抛出异常),因为目前 Jacksonnull 视为一个值,因此,这不违反@JsonProperty(required=true)指定的合约

我需要 username 字段始终出现在我的 json 中。

我尝试过将@NotNulljavax.validation:validation-api 一起使用,但这似乎不起作用。

这是一个 spring-boot 1.5.2 应用程序。

附言
请随时建议其他可用的 API 或编辑问题以使其更好。

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

    你可以使用一些链接来帮助你。

    mapper.setSerializationInclusion(Include.NON_NULL);
    

    或:

      @JsonInclude(Include.NON_NULL)
        class User
        {
        private String username;
        private String dob;
        private String email;
        ......
        .......
        }
    

    【讨论】:

    • 将进行序列化。如果用户名为空,我希望序列化停止。
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 2018-05-31
    相关资源
    最近更新 更多