gpt4 book ai didi

java - 将 jsonObject 转换为模型对象时如何检测缺少的字段

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

我正在使用网络服务发送一个 JsonObject。接收调用的方法具有模型对象的方法参数,用于传递相应的 JsonObject Input。 JsonObject 已成功转换为模型对象,但我无法测试来自模型对象的一些响应。

例如:如果输入 JSON 中缺少任何必填字段,或者如果输入 JSON 中的任何字段设置为 null,那么在这两种情况下,模型对象字段将变为

我无法检测到 null 是因为字段丢失还是字段被设置为 null

谁能给我一个解决方案?

我最后的出路是,我将接收方法参数输入作为 String 而不是我的模型对象,然后使用条件检查,检查输入字符串并相应地获得我的响应。但是我的 JSON 输入对象非常大,我希望有比这更好的解决方法。

这是一个Spring boot项目。

代码片段:

JSON Object being sent

{"orgType":null, "orgLocation": "Geneva" , //other fields}


@RequestMapping(value="/addOrganizations", method= RequestMethod.POST)
public ResponseEntity addOrganization(@RequestBody Organization organization){
// code goes here
}

如果我尝试

{"orgType":null, "orgLocation": "Geneva" , //other fields}

或:

{"orgLocation": "Geneva" , //other fields}

并在 addOrganization() 方法中检查调试器,然后在这两种情况下该值为 null

模型类:

public class Organization{

@JsonInclude(JsonInclude.Include.NON_EMPTY)
private String orgType;

private String orgLocation;

// other fields and getters and setters.

}

最佳答案

我正在浏览 StackOverflow 的链接,最后通过这个链接得到了答案

Jackson: What happens if a property is missing?

想法可能对其他人有帮助。

谢谢

关于java - 将 jsonObject 转换为模型对象时如何检测缺少的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47978381/

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