Cute Apple
본문 바로가기
개발/jsp

json xml 을 json 변환하는 3가지 방법

by 미댕댕 2021. 6. 29.

우선 Google Map API를 사용하기 위한 초기 setting 시작

- https://www.data.go.kr/index.do 의 api를 사용을 위해 해당 api의 서비스키를 가져와 대입한다.

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
public class PlaceServlet extends HttpServlet{
    SAXParserFactory factory;
    SAXParser saxParser;
    CultureHandler handler; 
    
    @Override
    public void init() throws ServletException {
        factory = SAXParserFactory.newInstance();
        try {
            saxParser = factory.newSAXParser(); //파서 생성
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //String result = loadData();
        
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        
        //xml 파싱을 위한 객체는 자바에서 이미 지원
        //요청하기 위한 파라미터 구성
        String ServiceKey="TPK6sq5VdCOFrijK99CmJHQCEVer9GwK4sxLvP6ED6dBExrBc6FO298QjQadJsw7C4sDZ8yBXJfsYZ%2FVT6LG0A%3D%3D";
        
        StringBuilder urlBuilder = new StringBuilder("http://api.visitkorea.or.kr/openapi/service/rest/KorService/locationBasedList"); /*URL*/
        urlBuilder.append("?" + URLEncoder.encode("ServiceKey","UTF-8"+ "="+ServiceKey); /*Service Key*/
        urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8"+ "=" + URLEncoder.encode("10""UTF-8")); /*한 페이지 결과 수*/
        urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8"+ "=" + URLEncoder.encode("1""UTF-8")); /*현재 페이지 번호*/
        urlBuilder.append("&" + URLEncoder.encode("MobileOS","UTF-8"+ "=" + URLEncoder.encode("ETC""UTF-8")); /*IOS(아이폰),AND(안드로이드),WIN(원도우폰), ETC*/
        urlBuilder.append("&" + URLEncoder.encode("MobileApp","UTF-8"+ "=" + URLEncoder.encode("AppTest""UTF-8")); /*서비스명=어플명*/
        urlBuilder.append("&" + URLEncoder.encode("arrange","UTF-8"+ "=" + URLEncoder.encode("A""UTF-8")); /*(A=제목순, B=조회순, C=수정일순, D=생성일순, E=거리순)*/
        urlBuilder.append("&" + URLEncoder.encode("contentTypeId","UTF-8"+ "=" + URLEncoder.encode("15""UTF-8")); /*관광타입(관광지, 숙박 등) ID*/
        urlBuilder.append("&" + URLEncoder.encode("mapX","UTF-8"+ "=" + URLEncoder.encode("126.981611""UTF-8")); /*GPS X좌표(WGS84 경도 좌표)*/
        urlBuilder.append("&" + URLEncoder.encode("mapY","UTF-8"+ "=" + URLEncoder.encode("37.568477""UTF-8")); /*GPS Y좌표(WGS84 위도 좌표)*/
        urlBuilder.append("&" + URLEncoder.encode("radius","UTF-8"+ "=" + URLEncoder.encode("1000""UTF-8")); /*거리 반경(단위m), Max값 20000m=20Km*/
        urlBuilder.append("&" + URLEncoder.encode("listYN","UTF-8"+ "=" + URLEncoder.encode("Y""UTF-8")); /*목록 구분 (Y=목록, N=개수)*/
        urlBuilder.append("&" + URLEncoder.encode("modifiedtime","UTF-8"+ "=" + URLEncoder.encode("""UTF-8")); /*콘텐츠 수정일*/
        
        //Http 요청을 위한 코드 
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type""application/json");//클라이언트 요청방식
        System.out.println("Response code: " + conn.getResponseCode());
        
        //첫번째 방법으로 호출하여 응답정보 구성
        String str=getJson3(conn);
        out.print(str);
        
        conn.disconnect();
    }
 
 
 
    //여기부터 메서드 
 
}
cs

 

XML parsing을 위한 handler class

 

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
package com.koreait.tourapp.controller.place;
 
import java.util.ArrayList;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
import com.koreait.tourapp.model.domain.Culture;
 
public class CultureHandler extends DefaultHandler{
    //실행부가 어디를 지나치고 있는지를 표시할 논리값들...선언
    private boolean isAddr1;
    private boolean isFirstimage;
    private boolean isMapx;
    private boolean isMapy;
    private boolean isTitle;
    
    ArrayList<Culture> list;
    Culture culture;
    
    //시작태그
    @Override
    public void startElement(String uri, String localName, String tag, Attributes attributes) throws SAXException {
        System.out.print("<"+tag+">");
        
        if(tag.equals("items")) { //vo를 담을 리스트 형을 준비
            list=new ArrayList<Culture>();
        }else if(tag.equals("item")) {
            culture = new Culture();
        }else if(tag.equals("addr1")) {
            isAddr1=true;
        }else if(tag.equals("firstimage")) {
            isFirstimage=true;
        }else if(tag.equals("mapx")) {
            isMapx=true;
        }else if(tag.equals("mapy")) {
            isMapy=true;
        }else if(tag.equals("title")) {
            isTitle=true;
        }
    }
    
    //태그사이 문자열 발견
    @Override
    public void characters(char[] ch, int start, int lengththrows SAXException {
        String data=new String(ch, start, length);
        System.out.print(data);
        if(isAddr1) {
            culture.setAddr1(data);
        }else if(isFirstimage) {
            culture.setFirstimage(data);
        }else if(isMapx) {
            culture.setMapx(Double.parseDouble(data));
        }else if(isMapy) {
            culture.setMapy(Double.parseDouble(data));
        }else if(isTitle) {
            culture.setTitle(data);
        }
    }
    
    //닫는 태그
    @Override
    public void endElement(String uri, String localName, String tag) throws SAXException {
        System.out.println("</"+tag+">");
        if(tag.equals("addr1")) {
            isAddr1=false;
        }else if(tag.equals("firstimage")) {
            isFirstimage=false;
        }else if(tag.equals("mapx")) {
            isMapx=false;
        }else if(tag.equals("mapy")) {
            isMapy=false;
        }else if(tag.equals("title")) {
            isTitle=false;
        }else if(tag.equals("item")) {
            list.add(culture);//완성된 Culture VO를 list에 담기!!
        }
    }
    
    //문서 종료 태그 
    @Override
    public void endDocument() throws SAXException {
        System.out.println("담겨진 결과 수는 "+list.size());
    }
    
}
 
cs

 

 

1. XML을 handler로 SAX Parsing 하여 String 화 -> String 을 json으로 parsing(Stringbuilder 이용)

 

 

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
//xml문자열을 파싱하여 자바객체로 변환한 후, 다시 json으로 변환하고 이 json을  json문자열로 클라이언트에게 응답
    public String getJson1(HttpURLConnection conn) {
        //요청에 의한 응답정보 가져오기
        //스트림을 이용한 파싱 
        String str=null;
        try {
            saxParser.parse(conn.getInputStream(), handler = new CultureHandler());
            //파싱이 종료되었고, 핸들러가 보유한  list를 접근해보기 
            //ArrayList  --> JSON으로 변환하여 클라이언트인 웹브라우저에 보내자!!!
            
            //자바의 객체를 JSON 문자열로 변환하는 과정을 개발자가 일일이 처리하지말고, Gson과 같은 라이브러리를 이용해보자
            //Map<String, List> map = new HashMap<String, List>();
            //map.put("items", handler.list);
            //Gson gson = new Gson();
            //str=gson.toJson(map);
            
            //out.print(str);
            
            StringBuilder sb=new StringBuilder();
 
            sb.append("{");
            sb.append("\"items\":[");
            for(int i=0;i<handler.list.size();i++) {
                Culture culture=handler.list.get(i); //VO 추출!!
                sb.append("{");
                sb.append("\"addr1\":\""+culture.getAddr1()+"\",");
                sb.append("\"firstimage\":\""+culture.getFirstimage()+"\",");
                sb.append("\"mapx\":"+culture.getMapx()+",");
                sb.append("\"mapy\":"+culture.getMapy()+",");
                sb.append("\"title\":\""+culture.getTitle()+"\"");
                
                if(i<handler.list.size()-1) {//size -1 보다 작을때까지 찍자
                    sb.append("},");
                }else {
                    sb.append("}");
                }
            }
            sb.append("]");
            sb.append("}");
            
            str=sb.toString();
            
            //out.print(sb.toString()); //클라이언트에게 응답시 사용할 컨텐츠 구성
            
        } catch (SAXException | IOException e) {
            e.printStackTrace();
        }
        return str;
    }
cs

 

 

 

 

2. XML을 handler로 SAX Parsing 하여 String 화 -> String 을 json으로 parsing(Gson 이용)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//xml을 파싱한 뒤 객체를 GSon을 이용하여 쉽게 json화
    public String getJson2(HttpURLConnection conn) {
        String str=null;
        try {
            saxParser.parse(conn.getInputStream(), handler = new CultureHandler());
            //자바의 객체를 JSON 문자열로 변환하는 과정을 개발자가 일일이 처리하지말고, Gson과 같은 라이브러리를 이용해보자
            Map<String, List> map = new HashMap<String, List>();
            map.put("items", handler.list);
            Gson gson = new Gson();
            str=gson.toJson(map);
        } catch (SAXException | IOException e) {
            e.printStackTrace();
        }
        return str;
    }
cs

 

3. XML을 바로 Json으로 변경

 

 

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
    //xml 을 바로 json 으로 변환
    public String getJson3(HttpURLConnection conn) {
        
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader rd;
            if(conn.getResponseCode() >= 200 && conn.getResponseCode() <= 300) {
                rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            } else {
                rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            rd.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        //xml 문자열을 자동을로 json 객체로 변환해보자!!
        
        JSONObject json=XML.toJSONObject(sb.toString()); //xml 스트링을 json 객체로 변환!!
        JSONObject res=(JSONObject)json.get("response"); //response key 가 가리키는 json 추출
        JSONObject body=(JSONObject)res.get("body");//body key 가 가리키는 json 추출
        JSONObject items=(JSONObject)body.get("items"); //items key가 가리키는 json 추출 
        //JSONArray item=(JSONArray)items.get("item"); //item key가 가리키는 json array 추출 
        //System.out.println("관광 아이템의 수는 "+item.length());
        return items.toString();
     }
cs
반응형

'개발 > jsp' 카테고리의 다른 글

json GSON 사용  (0) 2021.06.29
jsp Google Map api 사용  (0) 2021.06.28
jsp javaBean  (0) 2021.06.28
jsp 댓글 게시판(MyBatis / Ajax / Maven / Lombok) & 세션관리  (0) 2021.06.25
jsp 파일업로드 (oreilly / apache)  (0) 2021.06.23

댓글