我有一个具有该依赖项的SpringBoot应用程序:
<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从我的超文本标记语言发送了一个JSON对象,其中包含一些XRequest类型的字段(它是一个没有任何注释的普通POJO )。然而,我的JSON不是在我的控制器方法中构造到对象中的,它的字段是空的。
在我的控制器自动反序列化中,我错过了什么?
发布于 2016-10-26 03:55:13
Spring boot附带了Jackson的开箱即用功能,它将负责将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;
}发布于 2019-06-09 16:27:26
默认情况下,SpringBoot附带此功能。您只需在控制器方法的参数声明中使用@RequestBody注释,但与@so-random-dude的answer相比,您不必使用@JsonProperty注释字段,这不是必需的。
您只需为自定义XML对象类提供getter和setter。为了简单起见,我在下面贴了一个例子。
示例:
控制器方法声明:-
@PostMapping("/create")
public ResponseEntity<ApplicationResponse> createNewPost(@RequestBody CreatePostRequestDto createPostRequest){
//do stuff
return response;
}您的自定义XML对象类:
public class CreatePostRequestDto {
String postPath;
String postTitle;
public String getPostPath() {
return postPath;
}
public void setPostPath(String postPath) {
this.postPath = postPath;
}
public String getPostTitle() {
return postTitle;
}
public void setPostTitle(String postTitle) {
this.postTitle = postTitle;
}
}https://stackoverflow.com/questions/40247556
复制相似问题