๐ ์๋ต(Response) ๋ฐ์ดํฐ ๋ณด๋ด๊ธฐ
@ResponseBody ์ด๋ ธํ ์ด์ ์ด ๋ถ์ ๋ฉ์๋์์ Map์ ๋ฐํํ๋ฉด ์๋์ผ๋ก JSON ํํ๋ก ๋ณํ๋๋ค. (@RestController ํฌํจ)
๋ฐ๋๋ก JSON ์ ๋ณด๊ฐ @RequestBody ์ด๋
ธํ
์ด์
์ด ๋ถ์ ์ปจํธ๋กค๋ฌ๋ก ๋ณด๋ด์ง๋ฉด, Map ์ผ๋ก ์ ์ธ๋ ๋ณ์์ Json ์๋ฃํ์ ๋ฐ๋ก ๋ฐ์ ์ ์๋ค.
โซ๏ธ CMRespDto.java
@AllArgsConstructor
@Getter
public class CMRespDto<T> {
private int code; // 1 : ์ฑ๊ณต, -1 : ์คํจ
private String msg; // commit ๋ฉ์ธ์ง
private T data; // ์๋ต์ผ๋ก ๋ณด๋ผ ๋ฐ์ดํฐ
}
โซ๏ธ StudentRespDto.java
@Builder
@Getter
public class StudentRespDto {
private int studentCode;
private String studentName;
private int studentYear;
private String studentAddress;
private String studentPhone;
}
โซ๏ธ CMResponseController.java
์ปค๋ฐ ๋ฉ์์ง์ ํจ๊ป ์๋ต ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ด์ค๋ค.
@RestController
public class CMResponseController {
@GetMapping("/api/v1/students")
public Object getStudentList() {
List<StudentRespDto> students = new ArrayList<StudentRespDto>();
Map<String, Object> studentMap = new HashMap<String, Object>();
StudentRespDto student1 = StudentRespDto.builder()
.studentCode(20220001)
.studentName("์ ์งฑ๊ตฌ")
.studentYear(1)
.studentAddress("์นด์ค์นด๋ฒ ์")
.studentPhone("010-1111-1111")
.build();
students.add(student1);
StudentRespDto student2 = StudentRespDto.builder()
.studentCode(20220002)
.studentName("๊น์ฒ ์")
.studentYear(1)
.studentAddress("์นด์ค์นด๋ฒ ์")
.studentPhone("010-2222-2222")
.build();
students.add(student2);
// return students; โ ๋ฆฌ์คํธ ๋ฐํ ์ Json ํํ๋ก ๋ณํ ๋ถ๊ฐ๋ฅ
// โญ ํค ๊ฐ์ ์ฃผ๊ธฐ ์ํด StudentList๋ฅผ Map ์ ๋ฃ์ด์ค๋ค.
studentMap.put("students", students);
return studentMap; // ํด๋ผ์ด์ธํธ์์ Json ํํ๋ก ์๋ต๋๋ค.
}
@GetMapping("/api/v1/cm/data1")
public CMRespDto<?> getData() {
return new CMRespDto<String>(1, "๋ฐ์ดํฐ ์๋ต ์ฑ๊ณต", "ํ
์คํธ ๋ฐ์ดํฐ");
}
@GetMapping("/api/v1/cm/data2")
public CMRespDto<?> getData2() {
return new CMRespDto<Boolean>(-1, "๋ฐ์ดํฐ ์๋ต ์คํจ", false);
}
@GetMapping("/api/v1/cm/data3")
public CMRespDto<?> getData3() {
List<StudentRespDto> dtoList = new ArrayList<StudentRespDto>();
dtoList.add(StudentRespDto.builder().studentCode(1).build());
dtoList.add(StudentRespDto.builder().studentCode(2).build());
dtoList.add(StudentRespDto.builder().studentCode(3).build());
return new CMRespDto<>(1, "ํ์ ์ ๋ณด ๋ฆฌ์คํธ ๋ฐ์ดํฐ ์
๋๋ค.", dtoList);
// StudentList ๋ฅผ ํค ๊ฐ์ ์ฃผ๊ธฐ ์ํด Map ์ ๋ฃ์์์.
// ์ด ๊ฒฝ์ฐ CMRespDto๋ก ๋ณด๋ด ํค(data)๊ฐ ์์.
}
}
๐ข ์๊ฐ ๐ฆ