我有一个使用JSON的Spring Boot控制器:
@PostMapping(
value = "/shipdetails")
public ResponseEntity acceptShip(@RequestBody Ship ship, HttpServletRequest request) {
shipService.checkShip(ship);
return new ResponseEntity<>(HttpStatus.OK);
}
存在对应的发货实体:
public class Ship implements Serializable {
@JsonProperty("Name")
private String name;
@JsonProperty("Owner")
private String owner;
public Ship(String name, String owner) {
this.name = name;
this.owner = owner; }
public Ship() {
}
// Getters and Setters removed for brevity
最后是这项服务:
@Service
public class ShipService {
Boolean checkShip(Ship ship) {
if (ship.getName().equals("Queen Mary")) {
// do something
}
//edited for brevity
无效JSON示例:
{
"name_wrong":"test name",
"owner":"Lloyds Shipping"
}
目前,如果我发送无效的JSON,我在堆栈跟踪上得到的错误是(服务层):Cannot invoke "String.equals(Object)" because the return value of "com.ships.Ship.getName()" is null
.
Jackson需要无参数的构造函数来进行反序列化.
在调试器中判断时,Ship实体有一个所有者集,但没有一个名称集,所以它不是整个实体是空的-只有一个字段.
我在没有缺省的无args构造函数的情况下try 了SHIP实体,因此您甚至不能将带有空字段的实体传递给服务,但是它失败了,甚至带有有效的JSON.
应该如何以及在哪里处理无效JSON的异常?