gpt4 book ai didi

java - Jackson 数据绑定(bind) JSON boolean 值转换

转载 作者:行者123 更新时间:2023-11-30 07:49:33 24 4
gpt4 key购买 nike

我正在使用 Jackson objectMapper 将 JSON 转换为对象并进行一些转换并将其转换回 JSON。

JSON 就像 { "id":"abc1243", "val":1, "isDel":true}

上面的val是int,isDel是boolean。

我的对象定义如下

public class MyObj{
private String id;
private String val;
private String isDel;
//getters and setters

}

当我将 JSON 转换为 MyObj 时,String id 和 Int val 绑定(bind)到 String 但 boolean 值未绑定(bind),因此我得到 null。

我使用下面的方法

   ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
try {
MyObj myObj = mapper.readValue(new File("/Users/sample.json"), MyObj.class);
}

我可以知道为什么 boolean 值没有绑定(bind)到 String 成员吗。

最佳答案

您可以有一个接受 boolean 值并进行必要转换的 setter

@JsonProperty("isDel")
public void setIsDel(boolean isDel) {
this.isDel = String.valueOf(isDel);
}

注意:这不会干扰接受 String 的 setter(注解告诉 Jackson 使用这个特定方法)

关于java - Jackson 数据绑定(bind) JSON boolean 值转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412266/

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