我有具有该依赖项的 Spring Boot 应用程序:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
我的控制器有一个方法如下:
@RequestMapping(value = "/liamo", method = RequestMethod.POST)
@ResponseBody
public XResponse liamo(XRequest xRequest) {
...
return something;
}
我通过 AJAX 从 HTML 发送一个 JSON 对象,其中包含一些 XRequest 类型对象的字段(它是一个没有任何注释的普通 POJO)。但是,我的 JSON 未在我的控制器方法中构建为对象,并且其字段为空。
我在控制器上自动反序列化错过了什么?
Spring Boot 附带了开箱即用的 Jackson,它将负责将 JSON 请求正文解封为 Java 对象
您可以使用 @RequestBody Spring MVC 注释将 JSON 字符串反序列化/解组为 Java 对象...例如。
Example
@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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)