[英]Spring Boot @RequestBody bind null values to a default value?
我有一个 Spring Boot 服务,它使用自定义 POJO 类作为 POST 请求正文。 当客户端将其中一个字段作为空值传递时,我希望将该值设置为 0。
@Data
public class CardAnswer {
private Integer answerId = 0; //should always be 0 and never set to null
private String value;
}
由以下控制器使用:
@RequestMapping(value = "/{category}", method = RequestMethod.POST)
public SalesPulseMResponse updateSecurity(@PathVariable(value = SalesedgeConstants.CATEGORY)
@RequestBody CardAnswer requestBody) {
return fooService.updateFieldsByCategory(category, requestBody);
}
Spring Boot 将为我处理从 JSON 到CardAnswer
的数据绑定,但是每当answerId
被传递为 null 时,我希望它保留 0。重视自己? 目前,如果客户端未在其请求 JSON 中传入此字段,它将保留默认值,但是,即使对于传入的空值,我也希望保留该默认值。
int
有这个属性,所以:
@Data
public class CardAnswer {
private int answerId;
private String value;
}
例子:
@Data
public class CounterRequest {
private final int int1;
private final int int2;
}
@Data
public class CounterResult {
private final int value;
}
@RestController
@RequestMapping(
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public class CounterRestController {
public static final String ADD_URL = "/counter/add";
@RequestMapping(value = ADD_URL,
method = RequestMethod.POST)
public CounterResult add(@RequestBody @Valid
CounterRequest counterRequest) {
return new CounterResult(counterRequest.getInt1() + counterRequest.getInt2());
}
}
跑:
$ curl -X POST -H "Content-Type: application/json" --data "{\"int1\":null,\"int2\":2}" localhost:8080/counter/add
{"value":2}
$ curl -X POST -H "Content-Type: application/json" --data "{\"int1\":1,\"int2\":2}" localhost:8080/counter/add
{"value":3}
您可以使用@JsonIgnore
@Data
public class CardAnswer {
@JsonIgnore
private Integer answerId = 0;
private String value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.