💻 개인공부 💻/Java

How to Convert Json to HashMap (feat. JAVA) [공공데이터포털API]

공대생 배기웅 2020. 8. 10. 17:43
반응형
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
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
 
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
 
 
class JusoUtil {
    public static ArrayList<HashMap<StringString>> jusoUtil(String confmKey, int currentPage, int countPerPage, String keyword,
            String resultType) throws Exception {
 
        String apiUrl = "http://www.juso.go.kr/addrlink/addrLinkApi.do?currentPage=" + currentPage + "&countPerPage="
                + countPerPage + "&keyword=" + URLEncoder.encode(keyword, "UTF-8"+ "&confmKey=" + confmKey
                + "&resultType=" + resultType;
        URL url = new URL(apiUrl);
 
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
        // 데이터를 buffer형식으로 읽음
 
        StringBuffer buffer = new StringBuffer();
        String tempStr = null// JSON형태
        while (true) {
            tempStr = br.readLine();
            if (tempStr == null) {
                break;
            }
            buffer.append(tempStr);
        } // tempStr에 JSON 데이터를 대입
 
        JSONParser jsonParser = new JSONParser();
        JSONObject jo = (JSONObject) jsonParser.parse(buffer.toString());
        JSONObject jo2 = (JSONObject) jo.get("results");
        JSONArray ja = (JSONArray) jo2.get("juso");
 
        ArrayList<HashMap<StringString>> arr = new ArrayList<HashMap<StringString>>();
        
        for (int i = 0; i < ja.size(); i++) {
            HashMap<StringString> map = new HashMap<StringString>();
            JSONObject object = (JSONObject) ja.get(i);
            
            Set<?> set = object.keySet();
            Iterator iterator = set.iterator();
            
            while(iterator.hasNext()) {
                String key = iterator.next().toString();
                map.put(key, (String) object.get(key));
            }
 
            arr.add(map);
        }
        return arr;
    }
}
 
 
 
public class JsonParsing {
 
    public static void main(String[]args) throws Exception {
        JusoUtil s = new JusoUtil();
        ArrayList arr1 = new ArrayList();
        ArrayList arr2 = new ArrayList();
        
        arr1 = s.jusoUtil("U01TX0FVVEgyMDE5MDcxNTE4MzE0MDEwODg4MjM="110"서교동 343-19","Json");
        
        for(int i=0;i<arr1.size();i++) {
            System.out.println(arr1.get(i));
            System.out.println(" ");
        }
    }
    
}
cs
728x90
반응형