Jam's story
[JSP] JSON 본문
JSON 데이터 형식을 xml 파일보다 더 많이 사용한다 이유? 가볍고 편리해서
JAava Script Object Notation ==JSON
js 객체 표시화 형식
가벼운 데이터 교환형식
기계가 구문분석하고 생성하기 쉽습니다.
클->ajax->서버
요청 json 파라미터
응답 json
json 두가지 구조
이름:값 쌍들의 모임
json 선언형식
{string 값 }
JSON 선언형식
{"age":20, "name":"", "array":[1,2,3,4,5], "이름":false, 이름:"true", "이름":"값","이름":"값"....}
//응용복합
"emp":[{}]
9.예
1)js Object 선언
var person={
name:"admin",
age:20,
addr:"seoul"
};
위의 jsObject 를 JSON 형식으로 변환
js object 표기방법
var personJSON= '{"이름":값 ,,,,, }';
var personJSON='{
"name":"admin",
"age":20.
"addr":"seoul",
"cars":[],
"color":"null",
"gender":"true"
}';
주의할점 :
js 문자열 : " " ' ' 홑따옴표나 쌍따옴표 안에 넣는다.
11.json파일
ㄱ.확장자: .json
ㄴ.MIME 유형 :
1.js object ->json변환
로컬 저장소 person 정보 저장
var person={name:"Admin", age:20, city:"seoul"};
function setPerson(){
//js object ->json변환
var personJSON=JSON.stringify(person);
console.log("personJSON:"+personJSON);
//저장하겠다
localStorage.setItem("personJSON", personJSON)
}
2.json -> js object 변환 JSON.parse()
function getPerson(){
//로컬에 저장된거 가져온값
var getpersonJSON=localStorage.getItem("personJSON");
//json->js object
var jsObj=JSON.parse(getpersonJSON);
//name
console.log("1. name"+jsObj.name);
//age
console.log("1. age"+jsObj.age);
//city
console.log("1. city"+jsObj.city);
}
버튼 클릭
ex04-dept.json -> js ajax->ex04.jsp 화면출력
ex04-dept.xml -> js ajax->ex04.jsp 화면출력
ex04-dept.xml
<?xml version="1.0" encoding="UTF-8"?><departments>
<dept>
<deptno>10</deptno>
<dname>ACCOUNTING</dname>
<loc>NEW YORK</loc>
</dept>
<dept>
<deptno>20</deptno>
<dname>RESEARCH</dname>
<loc>DALLAS</loc>
</dept>
<dept>
<deptno>30</deptno>
<dname>SALES</dname>
<loc>CHICAGO</loc>
</dept>
<dept>
<deptno>40</deptno>
<dname>OPERATIONS</dname>
<loc>BOSTON</loc>
</dept>
</departments>
ex04-dept.json
{
"departments":[
{"deptno":10, "dname":"ACCOUNTING", "loc":"NEW YORK"}
,{"deptno":20, "dname":"RESEARCH", "loc":"DALLAS"}
,{"deptno":30, "dname":"SALES", "loc":"CHICAGO"}
,{"deptno":40, "dname":"OPERATIONS", "loc":"BOSTON "}
]
}
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2022. 7. 1. - 오전 10:39:50</title>
<link rel="shortcut icon" type="image/x-icon" href="../images/SiSt.ico">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="httpRequest.js"></script>
</head>
<body>
<h3>ex04.jsp</h3>
<pre>
버튼 클릭
ex04_dept.json -> js ajax -> ex04.jsp 화면 출력
ex04_dept.xml -> js ajax -> ex04.jsp 화면 출력
</pre>
<button onclick="xmlAjax();">ex04_dept.xml js ajax -> 부서 table 생성 </button>
<br>
<button onclick="jsonAjax();">ex04_dept.json js ajax -> 부서 table 생성 </button>
<br>
<p id="demo"></p>
<script>
// 11:00 수업 시작
function jsonAjax(){
sendRequest("ex04_dept.json", null, callbackJson, "GET");
}
function xmlAjax(){
sendRequest("ex04_dept.xml", null, callback, "GET");
} // xmlAjax
function callbackJson(){
if ( httpRequest.readyState == 4 ) {
if ( httpRequest.status == 200 ) {
// json 데이터 응답 == 문자열
var deptJSON = this.responseText;
// json -> js object 변환
var deptJsObject = JSON.parse(deptJSON);
var deptArray = deptJsObject.departments;
var tblContent = "<table id='tblajax' border='1'>";
tblContent += "<tr><th>depnto</th><th>dname</th><th>loc</loc></tr>";
for (var i = 0; i < deptArray.length; i++) {
var dept = deptArray[i]; // {"deptno":10, "dname":"ACCOUNTING", "loc":"NEW YORK"}
tblContent += "<tr>";
tblContent += "<td>";
tblContent += dept.deptno;
tblContent += "</td>";
tblContent += "<td>";
tblContent += dept.dname;
tblContent += "</td>";
tblContent += "<td>";
tblContent += dept.loc;
tblContent += "</td>";
tblContent += "</tr>";
} // for
tblContent += "</table>";
document.getElementById("demo").innerHTML = tblContent;
} else {
alert("> Ajax 요청 실패 : " + httpRequest.status );
}
}
}
function callback(){
if ( httpRequest.readyState == 4 ) {
if ( httpRequest.status == 200 ) {
var xmlDoc = this.responseXML;
// alert( xmlDoc );
var tblContent = "<table id='tblajax' border='1'>";
tblContent += "<tr><th>depnto</th><th>dname</th><th>loc</loc></tr>";
// DOM 메서드 = 3가지 코어, html, xml DOM
// var cdList = xmlDoc.querySelectorAll("CATALOG CD");
var cdList = xmlDoc.getElementsByTagName("dept");
for( var i = 0 ; i < cdList.length ; i++ ){
tblContent += "<tr>";
tblContent += "<td>";
tblContent += cdList[i].getElementsByTagName("deptno")[0].childNodes[0].nodeValue;
tblContent += "</td>";
tblContent += "<td>";
tblContent += cdList[i].getElementsByTagName("dname")[0].childNodes[0].nodeValue;
tblContent += "</td>";
tblContent += "<td>";
tblContent += cdList[i].getElementsByTagName("loc")[0].childNodes[0].nodeValue;
tblContent += "</td>";
tblContent += "</tr>";
}// for
tblContent += "</table>";
document.getElementById("demo").innerHTML = tblContent;
} else {
alert("> Ajax 요청 실패 : " + httpRequest.status );
}
}
}
</script>
<!--
JSON 샘플
{
string:value
"name":"John" , string
"age": 30 , number
"pets": [ array
{ "animal":"dog", "name":"fido"}, object
{ "animal":"cat", "name":"test"},
{ "animal":"hamster", "name":"box"}
]
}
-->
</body>
</html>
'JSP' 카테고리의 다른 글
[JSP] MVC2모델을 이용한 로그인 구현 (0) | 2022.07.07 |
---|---|
[JSP] 구글 맵 api (0) | 2022.07.04 |
[JSP] AJAX (0) | 2022.06.30 |
[JSP] EmpDeptList를 MVC패턴으로 구현 (0) | 2022.06.29 |
[JSP] ServletContextListener 인터페이스 활용 방법 (0) | 2022.06.24 |