json - 同时验证 2 个 Json 字段是否为 Not Null
问题描述
我有以下 JSON 。在任何时间点,只有“汽车”或“自行车”字段之一可以为空。不能同时为两者。如何使用杰克逊注释验证 json。JSON 中的所有字段都是必填的
{
"name": "John",
"age": 30,
"car": "Toyota",
"bike": "Honda"
}
我的 Java Pojo 对象
public class Example
{
@JsonProperty("name")
public String name;
@JsonProperty("age")
public Integer age;
@JsonProperty("car")
public String car;
@JsonProperty("bike")
public String bike;
解决方案
根据您的需要,您可以使用javax.validation.constraints.NotBlank中的 @NotBlank;
public class Example
{
@NotBlank(message = "This field cannot be blank")
@JsonProperty("name")
public String name;
@JsonProperty("age")
public Integer age;
@JsonProperty("car")
public String car;
@JsonProperty("bike")
public String bike;
}
您也可以从同一个包中尝试 @NotNull 或 @NotEmpty。他们有一些差异,看看最适合你的情况。
推荐阅读
- python - 如何将 4 维 PyTorch 张量乘以 1 维张量?
- spring-kafka - Kafka Listener 上的千分尺定时注释
- python - 从 SQLAlchemy declarative_base 定义的表中选择
- jestjs - Jest-Puppeteer 为什么警告“测试运行完成后一秒钟 Jest 没有退出
- sql - 在oracle sql中使用plsql检查表中是否存在两个值
- symfony - Symfony Omines 数据表列选项“过滤器”
- javascript - 使用 Javascript 的弹跳动画?
- powershell - PowerShell 将变量输出添加到正则表达式组
- prolog - prolog 中复制的实现
- javascript - 如何根据javascript中另一个随机变量的结果来调节随机生成器中的字符串变量?