gpt4 book ai didi

java - 使用 Jackson 避免使用空字段的对象

转载 作者:行者123 更新时间:2023-11-30 06:48:59 24 4
gpt4 key购买 nike

如果我尝试反序列化对象类中缺少字段的 JSON 字符串,则在创建对象时该字段将设置为 null。我需要 Jackson 在发生这种情况时抛出异常,这样我就不必在每个对象中实现 assertNotNullFields() 方法;即 JSON 字符串输入必须定义类中的所有字段,否则会抛出 JsonProcessingException

对象映射器配置:

objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

JSON 对象:

public class LogInUser {
public String identifier, password;
public LogInUser() {}
}

根据我的配置,这可能吗?

最佳答案

您可以尝试在您的 LogInUser 类中使用 JsonCreator,如上所述 here 。当引入您在问题中提出的代码时,它看起来像这样:

public class LogInUser {

@JsonCreator
public LogInUser(@JsonProperty(value = "identifier", required = true) String identifier, @JsonProperty(value = "password", required = true) String password) {
this.identifier = identifier;
this.password = password;
}

public String identifier, password;
public LogInUser() {}

}

当一个或多个值为 null 时,应该抛出异常。

关于java - 使用 Jackson 避免使用空字段的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43174097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com