Spring Boot自动JSON到控制器对象
我有SpringBoot应用程序与该依赖项:
org.springframework.boot spring-boot-starter-jersey org.springframework.boot spring-boot-starter-security org.springframework.boot spring-boot-starter-web
我在我的控制器上有一个方法如下:
@RequestMapping(value = "/liamo", method = RequestMethod.POST) @ResponseBody public XResponse liamo(XRequest xRequest) { ... return something; }
我通过AJAX从我的HTML发送一个JSON对象,其中包含一些XRequest类型对象的字段(它是一个没有任何注释的普通POJO)。 但是我的JSON没有在我的控制器方法中构造成对象,并且其字段为空。
我错过了我的控制器的自动反序列化?
Spring启动时带有Spring开箱即用,它将负责将JSON请求体解封为Java对象
您可以使用@RequestBody Spring MVC注释来将json字符串解组为Java对象…例如。
例
@RestController public class CustomerController { //@Autowired CustomerService customerService; @RequestMapping(path="/customers", method= RequestMethod.POST) @ResponseStatus(HttpStatus.CREATED) public Customer postCustomer(@RequestBody Customer customer){ //return customerService.createCustomer(customer); } }
使用@JsonProperty使用相应的json字段名称注释实体成员元素。
public class Customer { @JsonProperty("customer_id") private long customerId; @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; @JsonProperty("town") private String town; }