get json data -- JSP, SPRING




JSON을 파싱하기 위해 json-simple-1.1.1.jar 사용했던데 심플하게 가져올 수 있어 맘에 든다.

<%@ page import="org.json.simple.*" %>
<%@ page import="org.json.simple.parser.*" %>

public String getJSON(String url, int timeout) {
  
     try
     {
         URL u = new URL(url);
         HttpURLConnection c = (HttpURLConnection) u.openConnection();
        
         c.setRequestMethod("GET");
         c.setRequestProperty("Content-length", "0");
         c.setUseCaches(false);
         c.setAllowUserInteraction(false);
         c.setConnectTimeout(timeout);
         c.setReadTimeout(timeout);
         c.connect();
        
         int status = c.getResponseCode();

         switch (status)
         {
             case 200:
             case 201:
                 BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream(), "UTF-8"));
                 StringBuilder sb = new StringBuilder();
                 String line;
                
                 while ((line = br.readLine()) != null) {
                     sb.append(line+"\n");
                 }
                 br.close();
                
                 return sb.toString();
         }
     }
     catch (MalformedURLException e) {
         System.out.println(e.getMessage());
     }
     catch (IOException e) {
         System.out.println(e.getMessage());
     }
     catch (Exception e) {
      System.out.println(e.getMessage());      
     }
    
     return null;
}


String data = getJSON("
http://openapi.xxx.com/api1", 30000);

JSONParser parser = new JSONParser();
Object obj = parser.parse(data);
  
JSONObject jo = (JSONObject)obj;
JSONObject roadRoot = (JSONObject)jo.get("ROOT"); // ROOT항목
String totalCnt = roadRoot.get("total_count").toString(); // ROOT항목안에 total_count항목

JSONArray arrElement = (JSONArray)roadRoot.get("element"); // 배열형태의 element항목

for(int i=0; i<arrElement.size(); i++) {
   JSONObject j = (JSONObject)arrElement.get(i);
   String name = (String)j.get("name").toString(); // 배열안에 name항목
   .......
}


덧글

댓글 입력 영역