feat : Map -> DTO 컨버터
1. 기본모드 (느슨함, 필드 없으면 그냥 null) 2. 스트릭트모드 (엄격함, 필드 안맞으면 익셉션) 3. 가독 (세번째 파라미터가 뭔지 들어가전에 알수 없어서 헬퍼 매서드 추가)pull/34/head
parent
c7c5b1845a
commit
98a1901f3a
@ -0,0 +1,7 @@
|
|||||||
|
package egovframework.exception;
|
||||||
|
|
||||||
|
public class DtoConvertException extends RuntimeException {
|
||||||
|
public DtoConvertException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,53 @@
|
|||||||
|
package egovframework.util;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectReader;
|
||||||
|
import egovframework.exception.DtoConvertException;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class DtoConverter {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map<String, Object> → DTO 변환
|
||||||
|
* unknown 필드 허용
|
||||||
|
*/
|
||||||
|
public <T> T toDto(Map<String, Object> body, Class<T> clazz) {
|
||||||
|
return toDto(body, clazz, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* strict모드 가독 헬퍼
|
||||||
|
* */
|
||||||
|
public <T> T toStrictDto(Map<String, Object> body, Class<T> clazz) {
|
||||||
|
return toDto(body, clazz, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map<String, Object> → DTO 변환
|
||||||
|
* @param strict true > unknown 필드에 대한 예외 발생
|
||||||
|
*/
|
||||||
|
public <T> T toDto(Map<String, Object> body, Class<T> clazz, boolean strict) {
|
||||||
|
try {
|
||||||
|
ObjectReader reader = objectMapper.readerFor(clazz);
|
||||||
|
if (strict) {
|
||||||
|
reader = reader.with(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||||
|
}
|
||||||
|
return reader.readValue(objectMapper.writeValueAsBytes(body));
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new DtoConvertException("DTO 변환 실패: " + clazz.getSimpleName(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue