如何返回自定义json文件而不是生成spring boot的默认json文件?
我有一个rest控制器进行授权:如何返回自定义json文件而不是生成spring boot的默认json文件?,spring,spring-boot,kotlin,Spring,Spring Boot,Kotlin,我有一个rest控制器进行授权: @RestController class AuthController { @PostMapping("/sign-up") fun signUp(@RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> { some code here.. } } 当我使用JSON发出/注册post请求时: { "role": "asdf
@RestController
class AuthController {
@PostMapping("/sign-up")
fun signUp(@RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> {
some code here..
}
}
当我使用JSON发出/注册post请求时:
{
"role": "asdf",
"email": "",
"password": ""
}
它返回一个由spring boot生成的答案:
{
"timestamp": "2020-02-12T05:45:42.387+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]\n at [Source: (PushbackInputStream); line: 3, column: 10] (through reference chain: foo.bar.xyz.model.SignUpRequest[\"role\"])",
"path": "/sign-up"
}
问题是:如何返回自定义JSON而不是默认生成的JSON
我想返回我的自定义JSON,如:
{
"result": "Invalid user data are given",
"errors": [
{
"fieldName": "ROLE",
"text": "Given role does not exist"
},
{
"fieldName": "EMAIL",
"text": "EMAIL is empty"
}
]
}
我建议您创建ErrorContrller,生成自定义json映射作为响应。然后,当您在注册方法中发现错误时,调用ErrorContrllers方法。
你可以从这里找到信息。最后我找到了一个解决方案。您应该创建一个注释@ControllerAdvice
的类,并创建一个注释@ExceptionHandler
的方法
@ControllerAdvice
class HttpMessageNotReadableExceptionController {
@ExceptionHandler(HttpMessageNotReadableException::class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleException(
exception: HttpMessageNotReadableException
): PostSignUpResponseError {
val errors = mutableListOf<PostSignUpResponseErrorItem>()
errors.add(
PostSignUpResponseErrorItem(
fieldNamePost = "Role",
text = "Given role does not exist"
)
)
return PostSignUpResponseError(
result = "Invalid user data are given",
errors = errors
)
}
}
无论如何,我仍然不知道如何将这个东西附加到某个PostMapping方法。网络上有很多例子。一个是
@ControllerAdvice
class HttpMessageNotReadableExceptionController {
@ExceptionHandler(HttpMessageNotReadableException::class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleException(
exception: HttpMessageNotReadableException
): PostSignUpResponseError {
val errors = mutableListOf<PostSignUpResponseErrorItem>()
errors.add(
PostSignUpResponseErrorItem(
fieldNamePost = "Role",
text = "Given role does not exist"
)
)
return PostSignUpResponseError(
result = "Invalid user data are given",
errors = errors
)
}
}
data class PostSignUpResponseError(
val result: String,
val errors: List<PostSignUpResponseErrorItem>
)
class PostSignUpResponseErrorItem(
val fieldNamePost: PostSignUpRequestFieldName,
val text: String
)