2.마크업언어/JSON

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