首页 > 解决方案 > 为 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

标签: jsonspring-bootkotlinspring-restcontroller

解决方案


推荐阅读