Skip to main content

Spring 接口同时支持JSON数据和Form表单数据

· One min read
Alan

如何让 Spring Boot 接口同时支持JSON数据和Form表单数据

via How to consume both JSON and URL encoded form data in REST endpoint (Spring Boot)

/**
* JSON: {"field1": "field1Value", "field2":"field2Value"}
* form-data: field1=field1Value&field2=field2Value
**/
@PostMapping(value = "/token", consumes = {"application/json", "application/x-www-form-urlencoded"})
public ResponseEntity<ResponseType> createToken(@RequestBody String payload) throws IOException {

// Map the input string to DTO using Jackson
ObjectMapper mapper = new ObjectMapper();
RequestDTO request = mapper.readValue(payload, RequestDTO.class);

//Rest of the code
}