-2

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

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

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

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

这是显示响应结果的代码片段

  • 控制器
 @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
)

谁能帮我解答一下,谢谢。

4

1 回答 1

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> {...}
于 2020-07-20T16:55:29.563 回答