목차
1.JSON
1. JSON
JSON(제이슨[1], JavaScript Object Notation)은 속성-값 쌍( attribute–value pairs and array data types (or any other serializable value)) 또는 "키-값 쌍"으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷이다. -위키백과-
쉽게 말해 정해진 문법에 맞게 데이터를 담아 전달 하게 되면 전달 받은 사람은 파싱하여 데이터들을 쉽게 꺼내서
사용 할수 있도록 도와주는 것이다.
ex)
1) 오브젝트 형식(단일 데이터)
{"key":"value","key":"value"...}
num | id | pw | name | tel |
1 | admin | hi1234 | kim | 010 |
위와 같은 데이터를 JSON 형태의 데이터로 변환 하게 되면 아래와 같다
{"num":1,"id":"admin","pw":"hi1234","name":"kim","tel":"010"}
2) 배열 형식(여러 데이터)
[ {"key":"value","key":"value"...} , {"key":"value","key":"value"...} ]
num | id | pw | name | tel |
1 | admin | hi1234 | kim | 010 |
2 | admin | hi1234 | kim | 010 |
위와 같은 데이터를 JSON 형태의 데이터로 변환 하게 되면 아래와 같다
[{"num":1,"id":"admin","pw":"hi1234","name":"kim","tel":"010"},{"num":2,"id":"admin","pw":"hi1234","name":"kim","tel":"010"}]
{"num":1}
value 타입이 정수이면 " 사용 하지 않고 그대로 표현 한다
{"id":"admin"}
value 타입이 문자열이면 " 사용 하여 표현 한다
이것을 하드코딩으로 작성하게 된다면 힘들고 오타도 많이 발생 할것이다(\"" 이런식으로 작성해야 하므로...)
org.json.jar 라이브러리를 사용하게 된다며 이러한 수고를 덜어 준다
1) json 형식에 맞는 데이터를 파싱 해준다
2) json 형식에 맞게 데이터 생성 해준다
오브젝트 형식일때( { } )는 JSONObject 을 사용 하고,
배열 형식( [ ] )일때는 JSONArray을 사용 한다.
1) json 형식에 맞는 데이터를 파싱 해준다
JSONObject 사용
try { //URL 접속 URL url = new URL("http://localhost:8090/web04json/json_selectOne2.do?num=2"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); if (con.getResponseCode() == 200) { System.out.println("200..."); //연결된 컨넥션에서 Reader 연결 InputStream is = con.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String str = null; StringBuilder sb = new StringBuilder(); //모든 데이터를 StringBuilder에 담기 while ((str = br.readLine()) != null) { sb.append(str); } System.out.println(sb.toString()); //Json 데이터 파싱 JSONObject obj = new JSONObject(sb.toString()); //Object에서 파상된 데이터 사용 System.out.print(obj.getInt("num") + " "); System.out.print(obj.getString("id") + " "); System.out.print(obj.getString("pw") + " "); System.out.print(obj.getString("name") + " "); System.out.println(obj.getString("tel") + " "); } else { System.out.println("fail..."); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
JSONArray 사용
try { URL url = new URL("http://localhost:8090/web04json/json_selectAll3.do"); HttpURLConnection con =(HttpURLConnection) url.openConnection(); if(con.getResponseCode()==200) { System.out.println("200..."); //URL에 접속 InputStream is = con.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String str = null; StringBuilder sb = new StringBuilder(); //접속된 URL에서 데이터 읽어와서 StringBuilder에 담기 while((str=br.readLine())!=null) { sb.append(str); } System.out.println(sb.toString()); //읽어 온 데이터를 JSONArray에 담기 JSONArray array = new JSONArray(sb.toString()); //파싱된 데이터 가져오기 for (int i = 0; i < array.length(); i++) { //JSONArray -> JSONObject -> 사용 //배열에 담긴 Object를 하나씩 꺼내서 obj에 담아서 사용 JSONObject obj = array.getJSONObject(i); System.out.print(obj.getInt("num")+" "); System.out.print(obj.getString("id")+" "); System.out.print(obj.getString("pw")+" "); System.out.print(obj.getString("name")+" "); System.out.println(obj.getString("tel")+" "); } }else{ System.out.println("fail..."); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
1) json 형식에 맞는 데이터를 파싱 해준다
JSONObject 사용
PrintWriter out = response.getWriter(); MemberDAO dao = new MemberDAOimpl(); MemberVO vo = new MemberVO(); vo.setNum(Integer.parseInt(request.getParameter("num"))); //DB에서 조회된 ROW 1개를 Object에 담는다 MemberVO vo2 = dao.selectOne(vo); //Object를 JSONObject로 변환 한다 JSONObject obj = new JSONObject(vo2); //출력하면 Json 형태로 출력 해준다 out.print(obj);
JSONArray 사용
PrintWriter out = response.getWriter(); //ggg MemberDAO dao = new MemberDAOimpl(); //DB에서 조회된 ROW들을 List에(오브젝트) 담는다 Listvos = dao.selectAll(); //List를 JSONArray로 변환 한다 JSONArray array = new JSONArray(vos); //출력하면 Json 형태로 출력 해준다 out.print(array);
편리한 JSON은 Collection을 지원해주기 때문에 List를 바로 전달 해줘도 된다.
이것을 이용하여 지난 로또 번호들을 가져 오는것도 가능 하다
http://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=NUM
NUM 부분에 원하는 회차를 입력하면 해당 회차의 당첨 번호가 나오게 된다
이것을 DB에 넣고 내맘 대로 통계를 내어 나만의 로또 프로그램을 만들 수 있다
'IT > JSP' 카테고리의 다른 글
JSP_Jquery (0) | 2018.09.14 |
---|---|
JSP_javascript (0) | 2018.09.12 |
JSP_환경구성 및 JSP파일 생성 실행 (0) | 2018.09.09 |