IT 성장일기

[Spring] DTO를 이용해 중첩된 구조의 JSON 객체 전달 받기 본문

Java/Spring

[Spring] DTO를 이용해 중첩된 구조의 JSON 객체 전달 받기

고 양 2025. 3. 18. 15:03
반응형
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, 위치 정보가 포함되어 있는 중첩된 구조의 엔터티를 가지는 사용자 일정 서비스를 개발하면서 접하게 되었는데,

아래와 같은 다양한 서비스에서 비슷한 사용 사례가 있을 것 같습니다.

  • 주문 (사용자 정보와 장바구니)
  • 수강신청 (학생 정보와 수강 신청한 강의 목록)

감사합니다!

반응형