我有一個列舉,我想使用自定義屬性對其進行序列化。它在我的測驗中有效,但在我提出請求時無效。
列舉應該使用 JsonValue 映射
enum class PlantProtectionSortColumn(
@get:JsonValue val propertyName: String,
) {
NAME("name"),
REGISTRATION_NUMBER("registrationNumber");
}
在測驗中,小寫字母按預期作業。
class PlantProtectionSortColumnTest : ServiceSpec() {
@Autowired
lateinit var mapper: ObjectMapper
data class PlantProtectionSortColumnWrapper(
val sort: PlantProtectionSortColumn,
)
init {
// this works
test("Deserialize PlantProtectionSortColumn enum with custom name ") {
val json = """
{
"sort": "registrationNumber"
}
"""
val result = mapper.readValue(json, PlantProtectionSortColumnWrapper::class.java)
result.sort shouldBe PlantProtectionSortColumn.REGISTRATION_NUMBER
}
// this one fails
test("Deserialize PlantProtectionSortColumn enum with enum name ") {
val json = """
{
"sort": "REGISTRATION_NUMBER"
}
"""
val result = mapper.readValue(json, PlantProtectionSortColumnWrapper::class.java)
result.sort shouldBe PlantProtectionSortColumn.REGISTRATION_NUMBER
}
}
}
但是在控制器中,當我用小寫發送請求時,我得到 400。但是當請求與列舉名稱匹配時它可以作業,但回應以小寫形式回傳。所以 Spring 不僅僅將 objectMapper 用于請求,而是在回應中使用它。
private const val RESOURCE_PATH = "$API_PATH/plant-protection"
@RestController
@RequestMapping(RESOURCE_PATH, produces = [MediaType.APPLICATION_JSON_VALUE])
class PlantProtectionController() {
@GetMapping("/test")
fun get(
@RequestParam sortColumn: PlantProtectionSortColumn,
) = sortColumn
}
uj5u.com熱心網友回復:
我相信 kqr 的回答是正確的,你需要配置轉換器,而不是 JSON 反序列化器。
它可能看起來像:
@Component
class StringToPlantProtectionSortColumnConverter : Converter<String, PlantProtectionSortColumn> {
override fun convert(source: String): PlantProtectionSortColumn {
return PlantProtectionSortColumn.values().firstOrNull { it.propertyName == source }
?: throw NotFoundException(PlantProtectionSortColumn::class, source)
}}
uj5u.com熱心網友回復:
在您的端點中,您決議的不是 json 正文,而是查詢引數,它們不是 json 格式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/494559.html
