【问题标题】:Spring Boot REST API display response results in the formatSpring Boot REST API 以格式显示响应结果
【发布时间】:2020-11-09 23:06:54
【问题描述】:

我想以如下格式显示响应结果:

[
"author":"Author",
"status_code":"200"
"message":"GET",
"description":"Description..."
"data":{
    "id":"123",
    "name":""My Name",
    ...   : ...
}
]

但我只显示每个数据结果如下:

[
  {
    "id":"123",
    "name":""My Name",
    ...   : ...
  }
]

这是显示响应结果的代码sn-p

  • 控制器
 @GetMapping(value = "categorie")
    fun getAllFoodCategories(@Param(value = "key") key:String): ResponseEntity<List<Category>> {

        if (key==AppUtils.APY_KEY){
            var foodCategories: List<Category> = foodCategoryRespository.findAll()
            return if(!foodCategories.isEmpty()){
                foodCategories.forEach { v ->
                    run {
                        logger.info(v.toString())
                    }
                }
                ResponseEntity(foodCategories, HttpStatus.OK)
            }else{
                ResponseEntity(HttpStatus.NO_CONTENT)
            }

        }else{
            return ResponseEntity(HttpStatus.UNAUTHORIZED)
        }
        
    }
  • 模型类
@Entity(name = "categories")
data class Category(
        @Id
        @Column(name = "id")
        val id: Int,
        @get: NotBlank
        @Column(name = "name")
        val name: String
)

谁能帮我解答,谢谢。

【问题讨论】:

  • 你能提供Category类吗?
  • 响应格式是JSON不是更好吗?
  • 既然您返回的是List&lt;Category&gt;,那么您希望authorstatus_code 等字段/值神奇地从哪里来?
  • @zlaval 我更新了课程类别,请查看帮助我
  • @Andreas 是的,我想我想像第一个代码 sn-p 一样显示 json 形式,

标签: java json spring spring-boot kotti


【解决方案1】:

您不能以列表的形式返回不同的元素,但可以以包含类别列表的对象的形式返回。像这样:

{
"author":"Author",
"status_code":"200"
"message":"GET",
"description":"Description..."
"data":[
    {
        "id":"123",
        "name":""My Name",
        ...   : ...
    }
 ]
}

为此,创建一个类似的模型:

data class MyResponse(
   val author: String,
   val statusCode: String,
   val message: String,
   val description: String,
   val data: List<Category>
)

然后返回:

fun getAllFoodCategories(@Param(value = "key") key:String): ResponseEntity<MyResponse> {...}

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 2020-02-24
    • 2022-07-24
    • 2020-04-02
    • 1970-01-01
    • 2019-01-01
    • 2018-07-15
    • 2017-12-05
    • 2022-01-23
    相关资源
    最近更新 更多