我试图在 spring boot 中将枚举值作为标头参数提供给我的其余端点@RestController。为此,我将杰克逊库放入我的build.gradle文件中,因为自动生成的枚举使用了杰克逊注释。我无法更改枚举代码(它是根据 openapi 规范自动生成的)。它看起来像这样:
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 + "'");
}
}
我用来测试的其余控制器如下所示:
@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 标头,而只是在代码中中断,我可以看到代码的第一行工作正常,字符串application/pdf被转换为,value因此ObjectMapper使用该方法完成了它的工作@JsonCreator。
青春有我
相关分类