[英]Spring Boot Automatic JSON to Object at Controller
我有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从我的HTML发送一个JSON对象,其中包含一些XRequest类型对象的字段(它是一个没有任何注释的普通POJO)。 但是我的JSON没有在我的控制器方法中构造成对象,并且它的字段为空。
我错过了我的控制器的自动反序列化?
Spring启动时带有弹出启动功能,它将处理Java对象的非编组JSON请求主体
您可以使用@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;
}
默认情况下,SpringBoot具有此功能。 您只需在控制器方法的参数声明中使用@RequestBody
注释,但与@ so-random-dude的答案相反,您不必使用@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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.