如何返回我的自定义json文件而不是生成Spring Boot的默认json文件? [英] How I can return my custom json file instead of default json file that generates spring boot?

查看:69
本文介绍了如何返回我的自定义json文件而不是生成Spring Boot的默认json文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个授权的休息控制器:

I have a rest controller for authorization:

@RestController
class AuthController {

    @PostMapping("/sign-up")
    fun signUp(@RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> {
       some code here..
    }
}

signUp 方法获取 SignUpRequest 模型作为请求正文. SignUpRequest 模型是:

The signUp method gets SignUpRequest model as a request body. SignUpRequest model is:

enum class Role {
    @JsonProperty("Student")
    STUDENT,
    @JsonProperty("Tutor")
    TUTOR
}

data class SignUpRequest(
    val role: Role,
    val email: String,
    val password: String
)

当我使用JSON发出/sign-up 发布请求时:

When I make /sign-up post request with JSON:

{
    "role": "asdf",
    "email": "",
    "password": ""
}

它会给我一个由Spring Boot生成的答案:

It returns me an answer that were generated by 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?

Question is: How I can return my custom JSON instead of that default generated JSON?

我想返回我的自定义JSON,例如:

I want to return my custom JSON, like:

{
  "result": "Invalid user data are given",
  "errors": [
    {
      "fieldName": "ROLE",
      "text": "Given role does not exist"
    },
    {
      "fieldName": "EMAIL",
      "text": "EMAIL is empty"
    }
  ]
}

推荐答案

我建议您创建ErrorContrller来生成自定义json映射作为响应.然后,当您在注册方法中发现错误时,请调用ErrorContrllers方法.您可以从以下链接

I suggest you to create ErrorContrller that generates custom json map as response. Then when you will catch an error in sign-up method, call ErrorContrllers method. You can find info from this link

这篇关于如何返回我的自定义json文件而不是生成Spring Boot的默认json文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆