Spring Boot中的ObjectMapper可以讀取字符串,但在解析標(biāo)頭時(shí)不起作用
我試圖在 spring boot 中將枚舉值作為標(biāo)頭參數(shù)提供給我的其余端點(diǎn)@RestController。為此,我將杰克遜庫(kù)放入我的build.gradle文件中,因?yàn)樽詣?dòng)生成的枚舉使用了杰克遜注釋。我無(wú)法更改枚舉代碼(它是根據(jù) openapi 規(guī)范自動(dòng)生成的)。它看起來(lái)像這樣:public enum DocumentTypes { APPLICATION_PDF("application/pdf"), APPLICATION_RTF("application/rtf"), APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT("application/vnd.oasis.opendocument.text"), APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT("application/vnd.openxmlformats-officedocument.wordprocessingml.document"), APPLICATION_VND_MS_WORD("application/vnd.ms-word"), TEXT_HTML("text/html"), TEXT_PLAIN("text/plain"); private String value; DocumentTypes(String value) { this.value = value; } @Override @JsonValue public String toString() { return String.valueOf(value); } @JsonCreator public static DocumentTypes fromValue(String text) { for (DocumentTypes b : DocumentTypes.values()) { if (String.valueOf(b.value).equals(text)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + text + "'"); }}我用來(lái)測(cè)試的其余控制器如下所示:@RestController@RequestMapping("/test")public class TestController { @Autowired private ObjectMapper objectMapper; @RequestMapping(path = "", method = RequestMethod.GET) public void test(@RequestHeader(value = "Accept", required = false) DocumentTypes targetFormat) throws IOException { DocumentTypes value = objectMapper.readValue("\"application/pdf\"", DocumentTypes.class); }}如果我不提供 Accept 標(biāo)頭,而只是在代碼中中斷,我可以看到代碼的第一行工作正常,字符串a(chǎn)pplication/pdf被轉(zhuǎn)換為,value因此ObjectMapper使用該方法完成了它的工作@JsonCreator。
查看完整描述