[英]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.