หลังจากเรากำหนด @RestController
ที่เหนือ class ของ controller ทำให้ object ที่ return จาก controller นั้นจะถูกแปลงไปเป็น JSON response ให้โดยอัตโนมัติ
อย่างไรก็ตาม ถ้าหากเราต้องการสร้าง template ครอบ object ที่ return จาก controller ทุกๆ controller ก่อนที่จะส่งเป็น JSON response ออกไป เรามีขั้นตอนดังนี้
- สร้าง Class สำหรับ JSON response template
package com.example.model.wrapper; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import org.springframework.http.HttpStatus; @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) public class ResultWrapper<T> { @JsonProperty("code") private Integer code; @JsonProperty("status") private HttpStatus status; @JsonProperty("message") private String message; @JsonProperty("data") private T data = null; public Result(Integer code, HttpStatus status, String message) { this.code = code; this.status = status; this.message = message; } public ResultWrapper(Integer code, HttpStatus status, T data) { this.code = code; this.status = status; this.data = data; } }