我的Sping Boot 应用程序中有2个控制器:RestControllerA使用snake_case返回JSON,RestController2使用camelCase返回JSON。
有什么方法可以轻松地配置它吗?我目前正在做一些丑陋的事情,像这样:
@RestController
class RestControllerA(
@Qualifier("objectMapperSnakeCase")
private val objectMapperSnakeCase: ObjectMapper <-- I shouldn't have to inject this in.
) {
@GetMapping("/test-endpoint-1")
fun endpoint1(): ResponseEntity<String> { <-- I shouldn't have to return a string.
val employee = Employee(...)
val jsonString = objectMapperSnakeCase.writeValueAsString(employee)
return ResponseEntity.ok().body(jsonString)
}
}
@RestController
class RestControllerB(
@Qualifier("objectMapperCamelCase")
private val objectMapperCamelCase: ObjectMapper <-- I shouldn't have to inject this in.
) {
@GetMapping("/test-endpoint-2")
fun endpoint2(): ResponseEntity<String> { <-- I shouldn't have to return a string.
val employee = Employee(...)
val jsonString = objectMapperCamelCase.writeValueAsString(employee)
return ResponseEntity.ok().body(jsonString)
}
}
我更喜欢:
@RestController
class RestControllerA {
@GetMapping("/test-endpoint-1")
@ObjectMapperToUse("objectMapperSnakeCase") <-- Nice and easy.
fun endpoint1(): Employee {
return Employee(...)
}
}
// Similar for RestControllerB with objectMapperCamelCase
1条答案
按热度按时间wdebmtf21#
AFAIK,唯一可以干净地实现这一点的方法是to use JSON Views,就像前面提到的here一样。