본문 바로가기

JSON/JSON 03, JSON-Simple Intro

JSON in Java, JSON-Simple

JSON 문자열을 다루는 자바 라이브러리, JSON-Simple
json_simple-1.1-all.zipjson_simple-1.1.jarjson2.js

json-simple-1.1.1.jar



배포 사이트 : https://code.google.com/archive/p/json-simple/
다운로드: http://json-simple.googlecode.com/files/json-simple-1.1.1.jar

JSON-Simple 라이브러리를 사용하기 위한 중요한 개념은 JSONObject는 Map 처럼 다루면 되고, JSONArray 는 List처럼 다루면 되므로 새로 학습해야 하는 개념이 거의 없기 때문에 부담 없이 사용할 수 있다


자바 응용프로그램에서 JSON문자열을 파싱하여 JSONObject로 다루기와 JSON문자열 생성 예

package org.kdea.java.json;


import org.json.simple.*;

import org.json.simple.parser.*;


public class JsonSimpleDemo {

public static void main(String[] args) {

/* JSON 문자열을 파싱하여 JSONObject 로 다루는 예 */

String jsonStr = 

"{" +

"\"name\":\"smith\", \"hobby\":[\"영화\",\"게임\",\"독서\"]" +

"}";

JSONParser jsonParser = new JSONParser();

try {

JSONObject jsonObj = (JSONObject)jsonParser.parse(jsonStr);

String name = (String) jsonObj.get("name");

System.out.println("이름:"+name);

JSONArray jsonArr = (JSONArray) jsonObj.get("hobby");

for(int i=0;i<jsonArr.size();i++){

String hobby = (String) jsonArr.get(i);

System.out.println(hobby);

}

} catch (ParseException e) {

e.printStackTrace();

}

/* JSON 문자열을 생성하는 예 */

JSONObject jsonObj = new JSONObject();

jsonObj.put("sender", "홍길동");

jsonObj.put("receiver", "Smith");

jsonObj.put("msg", "감사합니다");

String jsonSt = jsonObj.toJSONString();

System.out.println(jsonSt);

}

}



서버측에서 Java를 이용하여 JSON문자열을 AJAX 클라이언트에게 전달하면 클라이언트 측에서는 문자열을 다시 JSON객체로 변환하여 사용하는 예

Example 1 - Server side JSP encoding

service.jsp:

  <%@page contentType="text/html; charset=UTF-8"%> 
 
<%@page import="org.json.simple.JSONObject"%> 
 
<% 
   
JSONObject obj=new JSONObject(); 
    obj
.put("name","foo"); 
    obj
.put("num",new Integer(100)); 
    obj
.put("balance",new Double(1000.21)); 
    obj
.put("is_vip",new Boolean(true)); 
    obj
.put("nickname",null); 
   
out.print(obj); 
   
out.flush(); 
  %>

Please note that you need to place json_simple-1.1.jar in WEB-INF/lib before running the JSP. Then the client side will get the resulting JSON text.

Example 2 - Client side XMLHttpRequest

client.html:

<html> 
<head> 
 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head> 
<script type="text/javascript"> 
function createXMLHttpRequest(){ 
 
// See http://en.wikipedia.org/wiki/XMLHttpRequest    // Provide the XMLHttpRequest class for IE 5.x-6.x: 

  if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() { 
   
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {} 
   
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {} 
   
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {} 
   
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {} 
   
throw new Error( "This browser does not support XMLHttpRequest." )    }; 
 
return new XMLHttpRequest(); 
} 
var AJAX = createXMLHttpRequest(); 
function handler() { 
 
if(AJAX.readyState == 4 && AJAX.status == 200) { 
     
var json = eval('(' + AJAX.responseText +')'); 
      alert
('Success. Result: name => ' + json.name + ',' + 'balance => ' + json.balance); 
 
}else if (AJAX.readyState == 4 && AJAX.status != 200) { 
    alert
('Something went wrong...'); 
 
} 
} 
function show(){ 
  AJAX
.onreadystatechange = handler; 
  AJAX
.open("GET", "service.jsp"); 
  AJAX
.send(""); 
}; 
</script> 
<body> 
 
<a href="#" onclick="javascript:show();"> Click here to get JSON data from the server side</a> 
</html>