menuCd

 highMenuCd

 menuNm

 orderNo

 

 1001

 0

 고객

 1

 1002

 1001

 고객리스트

 2
 1003 1002 대기리스트 3
 1004 0 게시판 4
 1005 1004 자유게시판 5
 1006 1004 유머게시판 6


위와 같은 형식의 데이터를 DB에서 뽑아 냈을때 오른쪽과 같이 화면에 표현하고 싶었다.


우선 Tree는 jQuery기반의 드래그앤랍이 기능이 되는 "jquery.dynatree.js" 를 선택했다.


이제 위 2차원 배열형태의 데이터를 dynatree가 요구하는 데이터형태로 변환을 해야 한다.

요구하는 데이터형태는 트리형식으로 아래와 같은 스타일로 만들어주면 된다.


[

{"isFolder":"true","title":"고객","children":[

{"isFolder":"true","title":"고객리스트" }

...

    ]

....

]


위와 같은 형태로 만들려고 삽질 좀 하다가 javascript 기반으로 잘 만들어져있는 소스를 구글링을통해 발견하여 그것을 java기반으로 수정 하였습니다.

(http://programmingsummaries.tistory.com/250)





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
/**
 * JSON관련 가공에 필요한 함수들
 * @auther ddakker 2013. 12. 12.
 */
public class JsonUtil {
    private static final Log log = LogFactory.getLog(JsonUtil.class);
    /**
     * 2차원 배열의 부모/자식 관계의 데이터를 트리형식으로 재나열 한다.
     * @param list          2차원 배열
     * @param rootId        최상위 id
     * @param idKey         유니크한 키(id가 될 필드명)
     * @param pIdKey        부모키(pId가 될 필드명)
     * @param titleKey      메뉴명이 표시될 필드명
     * @return
     * @auther ddakker 2013. 12. 12.
     */
    public static List<Map<String, Object>> convertorTreeMap(final List<Map<String, Object>> list, String rootId, final String idKey, final String pIdKey, final String titleKey){
        return convertorTreeMap(list, rootId, idKey, pIdKey, titleKey, null);
    }
    /**
     * 2차원 배열의 부모/자식 관계의 데이터를 트리형식으로 재나열 한다.
     * @param list          2차원 배열
     * @param rootId        최상위 id
     * @param idKey         유니크한 키(id가 될 필드명)
     * @param pIdKey        부모키(pId가 될 필드명)
     * @param titleKey      메뉴명이 표시될 필드명
     * @param orderKey      정렬이 필요한경우 정령 필드명
     * @return
     * @auther ddakker 2013. 12. 12.
     */
    public static List<Map<String, Object>> convertorTreeMap(List inList, String rootId, final String idKey, final String pIdKey, final String titleKey, final String orderKey){
        List<Map<String, Object>> treeList = new ArrayList<Map<String,Object>>();   // 최종 트리
         
        if( inList == null || inList.size() == 0 throw new RuntimeException("List<Map> 데이터가 없습니다.");
        if( inList.get(0) == null )                 throw new RuntimeException("Map 데이터가 없습니다.");
         
        final List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); // 원본데이터(Bean일경우 Map으로 변환)
        Iterator iter;
        for( iter=inList.iterator(); iter.hasNext(); ) {
            try{
                Object obj = iter.next();
                if( obj instanceof Map ) {
                    list.add((Map<String, Object>) obj);
                }else{
                    list.add((Map<String, Object>) BeanUtils.describe(obj));
                }
            }catch (Exception e) {
                throw new RuntimeException("Collection -> List<Map> 으로 변환 중 실패: " + e);
            }
        }
         
         
        int listLength = list.size();
        int loopLength = 0;
        final int[] treeLength = new int[] { 0 };
         
        while ( treeLength[0] != listLength && listLength != loopLength++ ) {
            for ( int i=0; i<list.size(); i++ ) {
                Map<String, Object> item = list.get(i);
                if ( rootId.equals((String)item.get(pIdKey)) ) {
                    Map<String, Object> view = new HashMap<String, Object>(item);
                    view.put("title", item.get(titleKey));
                    view.put("children", new ArrayList<Map<String,Object>>());
                     
                    treeList.add(view);
                    list.remove(i);
                     
                    treeLength[0]++;
                     
                     
                    if( orderKey != null ){
                        Collections.sort(treeList, new Comparator<Map<String, Object>>(){
                            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                                // TODO Auto-generated method stub
                                return ((String)arg0.get(orderKey)).compareTo((String)arg1.get(orderKey));
                            }
                        });
                    }
                    view.put("isFolder", "true");
                     
                    break;
                }else{
                    new InnerClass(){
                        public void getParentNode(List<Map<String, Object>> children, Map<String, Object> item ) {
                            for ( int i=0; i<children.size(); i++ ) {
                                Map<String, Object> child = children.get(i);
                                if ( child.get(idKey).equals(item.get(pIdKey)) ) {
                                    Map<String, Object> view = new HashMap<String, Object>(item);
                                    view.put("title", item.get(titleKey));
                                    view.put("children", new ArrayList<Map<String,Object>>());
                                    ((List<Map<String,Object>>) child.get("children")).add(view);
                                     
                                    treeLength[0]++;
                                     
                                    list.remove(list.indexOf(item));
                                    view.put("isFolder", "true");
                                     
                                    if( orderKey != null ){
                                        Collections.sort(((List<Map<String,Object>>) child.get("children")), new Comparator<Map<String, Object>>(){
                                            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                                                // TODO Auto-generated method stub
                                                return ((String)arg0.get(orderKey)).compareTo((String)arg1.get(orderKey));
                                            }
                                        });
                                    }
                                    break;
                                }else{
                                    if( ((List<Map<String,Object>>) child.get("children")).size() > 0 ){
                                        getParentNode((List<Map<String,Object>>) child.get("children"), item);
                                    }
                                }
                            }
                        }
                    }.getParentNode(treeList, item);
                }
            }
        }
        return treeList;
    }
     
    public interface InnerClass {
        public void getParentNode(List<Map<String, Object>> list, Map<String, Object> item );
    }
     
}

+ Recent posts