【发布时间】:2018-06-08 18:22:48
【问题描述】:
我的流程如下。
输入 json 请求的某些字段设置为“”。我希望响应 json 也将这些字段设置为“”。 相反,这些字段被赋值为 null 或 0。
我需要什么: 如何设置字段以响应“”而不是 null 或 0?
代码:
JSON 请求:
{
userID: "ABC",
creationDate: "",
noOfItems: ""
}
Bean 定义:
class UserOrderDetails {
private String userID;
private LocalDate creationDate;
private int noOfItems;
public String getUserID() {
return this.userID;
}
public void setUserID(String userID) {
this.userID=userID;
}
public LocalDate getCreationDate() {
return this.creationDate;
}
public void setCreationDate(LocalDate creationDate) {
this.creationDate=userID;
}
public int getNoOfItems() {
return this.noOfItems;
}
public void setNoOfItems(int noOfItems) {
this.noOfItems=noOfItems;
}
}
控制器类:
class UserOrderCreationController {
@RequestMapping(value = "/createUserOrder", method = RequestMethod.POST)
public ResponseEntity<?> createUserOrder(@RequestBody UserOrderDetails userOrderDetails , @RequestHeader HttpHeaders headers) throws Exception{
//Some business logic to handle the user Order
return new ResponseEntity<UserOrderDetails>(userOrderDetails, HttpStatus.CREATED);
}
}
回应:
{
userID: "ABC",
creationDate: null,
noOfItems: 0
}
注意:我无法将 LocalDate、int - CreationDate 和 noOfItems 的数据类型更改为 String,因为它被许多其他类使用。
【问题讨论】:
-
LocalDate 不是 JSON 原生的。日期时间始终为字符串。更多细节在这里:stackoverflow.com/questions/10286204/the-right-json-date-format
标签: java json javabeans isnullorempty