json - 为 RestController 配置 ObjectMapper
问题描述
我的 Spring 启动应用程序中有 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
解决方案
推荐阅读
- python - 如何“最好”检查 csv 文件中是否出现字符串/单词
- javascript - 需要 IE 填充程序的 Angular 5 和 IE11 问题
- vba - VBA Query returning nulls
- python - { "detail": "方法 \"GET\" 不允许。" }
- c++ - CMAKE Boost 单元测试框架在 Mac 上不起作用
- javascript - 如果所有输入字段不为空,则播放视频
- java - 在 iOS-Objective C 上签名的数据在 Java 中验证时总是返回 false
- visual-studio - Visual Studio 中的这个框叫什么,如何禁用它?
- php - SQL 从表中获取值
- android - FirebaseUI for Auth,自定义布局仅响应设置为 AuthMethodPickerLayout 的视图