열기, 닫기 클릭 시 div 보였다 안보였다 하게 하기


HTML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<div class="guideBox">
  <p>검색조건<span class="textbtn">[열기]</span></p>
  <div style="display:none">
 
    <div>
      <dl>
        <dd>
          <select id="a" name="a">
            <option value="a1">A1</option>
            <option value="a2">A2</option>
            <option value="a3">A3</option>
          </select>
        </dd>
      </dl>
    </div>
 
  </div>
</div>
cs


Script
1
2
3
4
5
6
7
8
9
$(document).on("click",".guideBox > p",function(){
      if($(this).next().css("display")=="none"){
        $(this).next().show();
        $(this).children("span").text("[닫기]");
      }else{
        $(this).next().hide();
        $(this).children("span").text("[열기]");
      }
});
cs


테이블 tr, td 등 선택하기



<원본테이블>


▼위 원본 테이블 그리는 html 소스

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
<table summary="연립다세대 실거래가조회 결과입니다." id="rh_table" style="display: none;">                                         
    <caption>연립다세대 실거래가조회 목록 안내</caption>                                                                                                  
    <colgroup>                                                                                                                             
        <col width='*'>                                                                                                                    
        <col width='15%'>                                                                                                                  
        <col width='10%'>                                                                                                                  
        <col width='12%'>                                                                                                                  
        <col width='12%'>                                                                                                                  
        <col width='10%'>                                                                                                                  
        <col width='15%'>                                                                                                                  
        <col width='5%'>                                                                                                                   
        <col width='8%'>                                                                                                                   
    </colgroup>                                                                                                                            
    <thead>                                                                                                                                
        <tr>                                                                                                                               
            <th scope='col' rowspan='2'>단지</th>                                                                                            
            <th scope='col' rowspan='2'>법정동</th>                                                                                           
            <th scope='col' rowspan='2'>지번</th>                                                                                            
            <th scope='col' rowspan='2'>전용<br/>면적(㎡)</th>                                                                                  
            <th scope='col' rowspan='2'>대지권<br/>면적(㎡)</th>                                                                                 
            <th scope='col' colspan='3'><span class="searchYearMonth"><fmt:formatDate value="${dateTime}" pattern="yyyy년 M월"/></span></th
            <th scope='col' rowspan='2'>건축<br/>년도</th>                                                                                     
        </tr>                                                                                                                              
        <tr>                                                                                                                               
            <th scope='col'>계약일</th>                                                                                                       
            <th scope='col'>거래금액(만원)</th>                                                                                                  
            <th scope='col'>층</th>                                                                                                         
        </tr>                                                                                                                              
    </thead>                                                                                                                               
    <tbody>                                                                                                                                
        <tr>                                                                                                                               
            <td colspan='9'>검색결과가 없습니다.</td>                                                                                               
        </tr>                                                                                                                              
    </tbody>                                                                                                                               
</table>                                                                                                                                   
cs



그런데 표 자체는 그대로 두면서 

thead-tr-th 안의 글자를 바꾼다던가

thead-tr-th 추가 또는 삭제를 해서 테이블을 가공하고 싶을 때.



<가공된 테이블>


▼ 위 가공된 테이블처럼 원본테이블을 조작하려면

1
2
3
4
5
if ("대지권면적(㎡)" == $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").text()) {   
    $("#rh_table > thead > tr:nth-child(2) > th:nth-child(2)").html("보증금<br/>월세");       
                                                                                         
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").remove();                 
}                                                                                        
cs

thead 가 2줄인데 첫번째 tr에서 다섯번째 th 텍스트가 대지권면적인지?

맞다면 테이블 가공해야하므로 if문 안의 내용을 실행.

아니라면 테이블이 이미 가공된 상태이므로 if문 패스.


if문 안의 내용은

thead에서 두번째 tr을 찾아서 그 tr의 2번째 th를 찾아 거래금액(만원)을 보증금월세로 바꾸고.

대지권면적 th를 제거.



가공된 테이블을 다시 원본테이블로 바꾸려면?

1
2
3
4
5
6
7
8
9
if ("대지권면적(㎡)" != $("#rh_table > thead > tr:nth-child(1) > th:nth-child(5)").text()) {        
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(1)").html("법정동");                   
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(2)").html("지번");                    
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(3)").html("전용<br/>면적(㎡)");          
    $("#rh_table > thead > tr:nth-child(1) > th:nth-child(4)").html("대지권<br/>면적(㎡)");         
    $("#rh_table > thead > tr:nth-child(2) > th:nth-child(2)").html("거래금액(만원)");              
                                                                                              
    $("#rh_table > thead > tr:nth-child(1)").prepend("<th schope='col' rowspan='2'>단지</th>"); 
}                                                                                             
cs

thead > 첫번째 tr> 다섯번째 th 의 텍스트가 대지권면적이 아니면 if문 안의 내용을 실행.

append()는 뒤에 붙이는거고, prepend()는 앞에 붙이는건데 prepend() 이걸 쓰는 이유는

rowspan 이 없으면 th 위치를 지정할 수 있을 것 같은데

rowspan 대문에 th 위치 지정해서 th 추가하기가 쉽지 않아서..

th 텍스트를 바꿔주고 제일 앞에 th를 추가해주는 식으로 함.


java xml 파일을 json 으로 변환하기


깃허브

https://github.com/stleary/JSON-java


메이븐 추가

http://mvnrepository.com/artifact/org.json/json/20140107


참고 : 

http://blog.naver.com/yandul83/220432077444

http://stackoverflow.com/questions/1823264/quickest-way-to-convert-xml-to-json-in-java



pom.xml 추가

1
2
3
4
5
6
7
        <!-- To convert XML File in to JSON -->
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20140107</version>
        </dependency>
cs



Controller (java) 작성

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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.json.XML;
 
@RestController
public class ActualDealController {
 
    @Value("${test.dataGoKrKey}")
    private String dataGoKrKey;
 
    //아파트매매 실거래자료
    private static final String dataGoActualDeaAptTradeUrl = "http://openapi.molit.go.kr:8081/OpenAPI_ToolInstallPackage/service/rest/RTMSOBJSvc/getRTMSDataSvcAptTrade";//?_wadl&type=xml
 
    /**
     * api 통해 실거래가 가져오기
     * @param paramMap
     * @return
     * @throws Exception
     */
    @RequestMapping("/deal/getDealPrice.do")
    public Map<String, Object> getActualDealPrice(@RequestParam Map<String, Object> paramMap) throws Exception {
        System.out.println("### getActualDealPrice paramMap=>"+paramMap);
        Map<String, Object> resultMap = new HashMap<>();
 
        try {
 
            StringBuilder urlBuilder = new StringBuilder(dataGoActualDeaAptTradeUrl);
            urlBuilder.append("?"+URLEncoder.encode("ServiceKey""UTF-8")+"="+dataGoKrKey);
            urlBuilder.append("&"+URLEncoder.encode("DEAL_YMD""UTF-8")+"="+URLEncoder.encode(paramMap.get("DEAL_YMD").toString(), "UTF-8"));
            urlBuilder.append("&"+URLEncoder.encode("LAWD_CD""UTF-8")+"="+URLEncoder.encode(paramMap.get("LAWD_CD").toString(), "UTF-8"));
 
            URL url = new URL(urlBuilder.toString());
 
            System.out.println("###url=>"+url);
 
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type""application/json");
            System.out.println("Response Code:"+conn.getResponseCode());
 
 
            BufferedReader rd;
            if (conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            } else {
                rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
 
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line=rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
            conn.disconnect();
 
            org.json.JSONObject xmlJSONObj = XML.toJSONObject(sb.toString());
            String xmlJSONObjString = xmlJSONObj.toString();
            System.out.println("### xmlJSONObjString=>"+xmlJSONObjString);
 
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = new HashMap<>();
            map = objectMapper.readValue(xmlJSONObjString, new TypeReference<Map<String, Object>>(){});
            Map<String, Object> dataResponse = (Map<String, Object>) map.get("response");
            Map<String, Object> body = (Map<String, Object>) dataResponse.get("body");
            Map<String, Object> items = null;
            List<Map<String, Object>> itemList = null;
 
            items = (Map<String, Object>) body.get("items");
            itemList = (List<Map<String, Object>>) items.get("item");
 
            System.out.println("### map="+map);
            System.out.println("### dataResponse="+dataResponse);
            System.out.println("### body="+body);
            System.out.println("### items="+items);
            System.out.println("### itemList="+itemList);
 
            resultMap.put("Result""0000");
            resultMap.put("numOfRows", body.get("numOfRows"));
            resultMap.put("pageNo", body.get("pageNo"));
            resultMap.put("totalCount", body.get("totalCount"));
            resultMap.put("data", itemList);
 
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.clear();
            resultMap.put("Result""0001");
        }
 
        return resultMap;
    }
}
 
cs


StringBuilder sb 출력하면 아래와 같이 xml 파일 형식이다.




이대로 java 에서 사용할 수 없기에...


org.json.JSONObject xmlJSONObj = XML.toJSONObject(sb.toString());

String xmlJSONObjString = xmlJSONObj.toString();

xml 파일 내용을 json 으로 파싱, string 으로 찍어보면 아래와 같다.




response 안에 header, body 가 있고

body 안에 items, numOfRows, pageNo, totalCount 가 있다.

items 안에 내가 얻고자 하는 "조회결과 목록=item들"이 있다.


여기서 item 들만 추출해 List<Map<String, Object>> 형식으로 담기 위해 위해 아래와 같이 작성한 것이다.


            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = new HashMap<>();
            map = objectMapper.readValue(xmlJSONObjString, new TypeReference<Map<String, Object>>(){});
            Map<String, Object> dataResponse = (Map<String, Object>) map.get("response");
            Map<String, Object> body = (Map<String, Object>) dataResponse.get("body");
            Map<String, Object> items = null;
            List<Map<String, Object>> itemList = null;
 
            items = (Map<String, Object>) body.get("items");
            itemList = (List<Map<String, Object>>) items.get("item");



저 깃허브는 찾았어도

pom.xml에 메이븐 dependency 추가하는거 찾는다고 오래걸렸다 ㅠ


+ Recent posts