简体   繁体   中英

Spring Boot REST API display response results in the format

I want to display the response result in the following format:

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

But I only display each data result as follows:

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

This is the code snippet that displays the response result

  • Controller
 @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)
        }
        
    }
  • The model class
@Entity(name = "categories")
data class Category(
        @Id
        @Column(name = "id")
        val id: Int,
        @get: NotBlank
        @Column(name = "name")
        val name: String
)

Can someone help me with the answer, Thanks you.

You can't return different elements as a list, but you can return as an object, which contains a list of category. Like this:

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

For this, create a model like:

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

Then return with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM