개발 공부/Spring

[Spring] VO 객체를 map으로 변환하기

Cydin 2019. 2. 27. 02:01
note

API를 만들다보니 모델 객체를 response 할 때 추가적인 데이터를 넣어 주어야 할 상황이 계속 생겼는데 편리하게 전환해주는 메소드가 없어 다른 코드들을 참고하여 직접 구현하였다. 다른 프로젝트에서도 사용할 일이 있을것같아 포스팅한다.

  • Map으로 변환하고 싶지 않은 컬럼들은 String[]로 전달해주면 된다.

구현 코드

  • DomainToMap.java

    /**
     * vo를 map형식으로 변환해서 반환
     * @param vo VO
     * @return
     * @throws Exception
     */
    public static Map<String, Object> domainToMap(Object vo) throws Exception {
        return domainToMapWithExcept(vo, null);
    }
    
    /**
     * 특정 변수를 제외해서 vo를 map형식으로 변환해서 반환.
     * @param vo VO
     * @param arrExceptList 제외할 property 명 리스트
     * @return
     * @throws Exception
     */
    public static Map<String, Object> domainToMapWithExcept(Object vo, String[] arrExceptList) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        BeanInfo info = Introspector.getBeanInfo(vo.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            Method reader = pd.getReadMethod();
            if (reader != null) {
                if(arrExceptList != null && arrExceptList.length > 0 && isContain(arrExceptList, pd.getName())) continue;
                result.put(pd.getName(), reader.invoke(vo));
            }
        }
        return result;
    }
    public static Boolean isContain(String[] arrList, String name) {
        for (String arr : arrList) {
            if (StringUtils.contains(arr, name))
                return true;
        }
        return false;
    }