gpt4 book ai didi

java - 空 JSON 字段(Java 模型中的 boolean/可为空字段)正在转换为 null

转载 作者:太空宇宙 更新时间:2023-11-04 09:27:13 25 4
gpt4 key购买 nike

我有一个具体要求,

  • 如果请求 JSON 正文中完全不存在( boolean 类型)字段,则该请求有效。
  • 如果此字段设置为 boolean 值(truefalse),那么它显然是有效的。
  • 如果该字段具有非 boolean 值,则应抛出异常。
  • 如果该字段具有值,它应该抛出异常

尽管如果通过类型检查字段为非 boolean 值,Java 模型会引发异常,空值仍会被转换为 null。相反,我需要能够区分它并抛出异常。如何才能实现这一目标?

这是我定义帖子正文模型的方式,并且我使用 AutoValue 生成器,因此我没有手动编写字段的 setter 函数。另外,我正在使用 fastxml 库。

@JsonProperty("indicator")
@Nullable
public abstract Boolean getIndicator();

我尝试定义自定义注释并编写逻辑来检查值是否为空,但它不起作用。

最佳答案

您需要禁用 MapperFeature.ALLOW_COERCION_OF_SCALARS在像您这样的情况下允许强制的功能。请参阅下面的示例:

import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonApp {

public static void main(String[] args) throws Exception {
String json = "{\"indicator\":\"\"}";

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
System.out.println(mapper.readValue(json, BaseClass.class));
}
}

class BaseClass {
private Boolean indicator;

public Boolean getIndicator() {
return indicator;
}

public void setIndicator(Boolean indicator) {
this.indicator = indicator;
}

@Override
public String toString() {
return "BaseClass{" +
"indicator=" + indicator +
'}';
}
}

上面的代码打印:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot coerce empty String ("") to Null value for type java.lang.Boolean (enable MapperFeature.ALLOW_COERCION_OF_SCALARS to allow) at [Source: (String)"{"indicator":""}"; line: 1, column: 14] (through reference chain: BaseClass["indicator"])

关于java - 空 JSON 字段(Java 模型中的 boolean/可为空字段)正在转换为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532574/

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