IT 성장일기
[Spring] DTO를 이용해 중첩된 구조의 JSON 객체 전달 받기 본문
반응형
DTO를 이용해 중첩된 구조의 JSON 객체 전달 받기
객체 안에 또 객체가 들어있는, 중첩된 구조의 객체를 JSON과 DTO를 이용해 주고받는 예제입니다.
예제
Client
JSON 객체는 아래와 같은 구조로 이루어져 있습니다.
let dto =
{
master : {
title ,
description ,
} ,
url : {
id ,
url ,
} ,
location : {
id ,
lat ,
lon ,
}
}
Server
JSON과 매핑시키기 위해 동일한 구조로 dto를 작성해야합니다. (롬복 애너테이션 등은 생략하겠습니다.)
public class Dto {
private Master master;
private List<Url> url;
private List<Location> location;
}
public class Master {
private String title;
private String description;
}
public class Url {
private long id;
private String url;
}
public class Location {
private long id;
private String lat;
private String lon;
}
컨트롤러에서는 아래처럼 dto를 이용해 요청을 받겠습니다.
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ResponseEntity<String> save(@RequestBody Dto dto, HttpServletRequest request) throws Exception {
try {
service.save(dto);
return ResponseEntity.ok("Success");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error: " + e.getMessage());
}
}
컨트롤러에서 dto를 클라이언트로 전달하는 예제도 작성해보겠습니다.
@RequestMapping(value = "/get", method = RequestMethod.POST)
public ResponseEntity<Dto> get(@RequestBody Dto dto, ModelMap model, HttpServletRequest request) throws Exception {
try {
Dto data = service.get(dto);
return ResponseEntity.ok(data != null ? data : new Dto());
} catch (Exception e) {
model.addAttribute("errorMessage", "상세 정보를 불러오는 중 문제가 발생했습니다.");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
많은 부분이 생략된 예제지만 모두들 알잘딱깔센 필요한 맥락만 잘 캐치해 가시리라 믿겠습니다. ^0^...
마치며
저의 경우는 일정 정보에 URL, 위치 정보가 포함되어 있는 중첩된 구조의 엔터티를 가지는 사용자 일정 서비스를 개발하면서 접하게 되었는데,
아래와 같은 다양한 서비스에서 비슷한 사용 사례가 있을 것 같습니다.
- 주문 (사용자 정보와 장바구니)
- 수강신청 (학생 정보와 수강 신청한 강의 목록)
감사합니다!
반응형
'Java > Spring' 카테고리의 다른 글
[Spring] There is no getter for property named 'url' in 'class java.lang.String' (1) | 2025.03.11 |
---|---|
[Spring] AJAX로 화면에 뷰 템플릿 추가하기 (2) | 2024.12.13 |
[Spring] Fetch API로 사용자 정보 일치 여부 확인하기 (feat. 403 Error) (0) | 2023.09.08 |
[Spring] 스프링부트에서 서버 재시작 없이 클래스 변경 사항 반영하기 (0) | 2023.09.08 |
[Spring] BeanDefinitionStoreException이 발생하는 이유 (0) | 2023.09.08 |