![](/img/trans.png)
[英]@RequestBody not mapping JSON to Java Object - Spring Boot
[英]Spring boot @RequestBody default POJO mapping behavior?
我有一個 java class 帶有大寫字段名稱,其中一些帶有下滾動,如下所示:
public class DATADto {
private String UPPERCASE;
private String UNDER_SCROLL;
public String getUPPERCASE() { return UPPERCASE; }
public void setUPPERCASE(String s) { UPPERCASE = s; }
...//setters and getters
}
and I used this in a rest endpoint that accepts json in a spring rest controller:
@RestController
@RequestMapping({"/api/path"})
public class MyRestController {
@PostMapping(path = {"/Data"}, consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> useDATADto(@RequestBody DATADto aDATADto ) {
//do something
}
}
我需要默認發送哪些 JSON 字段,為什么?
這將取決於 Jackson 屬性命名策略。 默認值為LOWER_CAMEL_CASE
,因此您的請求正文應如下所示:
{
"uppercase": "test",
"under_scroll": "test"
}
有關 Jackson 命名策略的所有可能配置,請參閱文檔«Class PropertyNamingStrategy»
如果您使用的是 Spring,您可以使用此屬性來配置命名策略:
spring.jackson.property-naming-strategy
另一種可能的方式是 bean 配置:
@Bean
public Jackson2ObjectMapperBuilder jacksonBuilder() {
Jackson2ObjectMapperBuilder jacksonMapper = new Jackson2ObjectMapperBuilder();
jacksonMapper.propertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
return jacksonMapper;
}
附加說明:
您當前的命名方法不遵循 Java 代碼約定。 如果您需要使用某些特定命名格式處理 JSON,最好在 POJO 的字段上使用@JsonProperty
注釋。
請看下面的例子:
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class DATADto {
@JsonProperty("UPPERCASE")
private String uppercase;
@JsonProperty("UNDER_SCROLL")
private String underScroll;
}
您應該使用此請求正文向/api/path/data
發送發布請求:
{
"uppercase": "YOUR_VALUE",
"under_scroll": "YOUR_VALUE"
}
故事是這樣的。。
Spring Boot 默認使用 Jackson ObjectMapper 對 Java 對象進行序列化和反序列化。
在這種情況下,序列化是指將 java 對象轉換為 json,反序列化是相反的過程。
關於@RequestBody
注解, 文檔中寫了以下內容:
指示方法參數的注釋應綁定到 web 請求的主體。 請求的主體通過 HttpMessageConverter 傳遞,以根據請求的內容類型解析方法參數。 或者,可以通過使用 @Valid 注釋參數來應用自動驗證。
簡而言之, @RequestBody
注釋告訴 Spring 將傳入的請求正文反序列化為作為參數傳遞給處理程序方法的 object。 Spring 使用MessageConverter實現此目的
Since Spring Boot uses Jackson
by default for serializing and deserializing request and response objects in your REST APIs, and Jackson uses MappingJackson2HttpMessageConverter
, so that will be message converter implementation that spring will use. 您可以在此處閱讀更多相關信息。
The important thing is that Jackson uses Java Bean naming conventions to figure out the json properties in a Java class. Acutally 它使用默認的PropertyNamingStrategy
。 以下是文檔中寫的內容:
在沒有注冊的自定義策略的情況下,使用默認的 Java 屬性命名策略,它保留字段名稱,並從方法中刪除 set/get/is 前綴(以及小寫的大寫字符的初始序列)。
因此,由於您沒有設置任何命名策略,它將使用默認策略。
因此,如果您發送這樣的有效負載:
{
"uppercase": "YOUR_VALUE",
"under_scroll": "YOUR_VALUE"
}
那行不通,你會得到異常,因為 jackson 不會在你的 class 中找到under_scroll
屬性,它會尋找under_SCROLL
,因此這個有效載荷:
{
"uppercase": "YOUR_VALUE",
"under_SCROLL": "YOUR_VALUE"
}
將工作。
要更改默認PropertyNamingStrategy
,請查看這篇文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.