Request to Dto

최종윤·2023년 5월 24일
0

프로젝트

목록 보기
9/13

hashtag가 "{"tag1", "tag2"}" 형식으로 Json 데이터를 요청으로 받는데, JSON 데이터에서 받은 string을 Hashtag로 변환해야 한다.
기존 hashtag를 DiaryDto를 Set(HashtagDto)를 필드로 지정하여서 사용했기 때문에 DiaryDto를 set(string)으로 수정하면 DiaryDto를 사용하던 Service코드에 문제가 생길 수 있을 것같아 DiaryReqeust 라는 Dto를 새로 만들었다.

public class DiaryRequest{
    String title;
    String weather;
    @JsonProperty("hashtag")
    Set<String> hashtagNames;
    String mood;

    public static DiaryRequest of(String title, String weather, Set<String> hashtagNames, String mood) {
        return new DiaryRequest(title, weather, hashtagNames, mood);
    }
    
    public DiaryDto toDto(){
        return DiaryDto.of(title, weather, hashtagNames.stream().map(HashtagDto::of).collect(Collectors.toUnmodifiableSet()), mood);
    }

hashtagNames라는 필드에 붙은 @JsonProperty는 요청으로 들어오는 Json데이터에서 hashtag라는 이름으로 데이터가 들어오는데 이름만 들어오고 객체를 받는 것이 아니므로 hashtagNames라는 이름을 붙이고 싶었다. @JsonProperty에 Json에 있는 키 이름을 적으면 이름이 다른 필드에 데이터를 넣을 수 있다.

profile
https://github.com/jyzayu

0개의 댓글