Spring

[Spring] JSON

아잠만_ 2024. 7. 30. 10:36

JSON

  • JavaScript Object Notation의 약자
  • 텍스트에 기반을 둔 데이터 저장 및 교환을 위한 구문
  • 자바스크립트 객체 표기법으로 작성된 텍스트
  • 브라우저와 서버 간에 데이터를 교환할 때 데이터는 텍스트
  • 모든 자바스크립트 객체를 JSON으로 변환하고 JSON을 서버로 보낼 수 있음
  • 서버에서 받은 JSON을 자바스크립트 객체로 변환할 수 있음

메서드

  • JSON.parse(text)
    • JSON형식 문자열 > JSON Object (deserialize)
  • JSON.stringify(obj)
    • JSON Object > JSON형식 문자열 (serialize)

JsonTest01.jsp (변환 예제)

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
let text = '{"name":"아잠만", "type":"먹보", "bir":"2020-06-30"}'
console.log(text);

// JSON.parse : JSON형 text를 JSON Object로 변환
let obj = JSON.parse(text);
console.log(obj);

// JSON.stringify : JSON Object를 JSON형 text로 변환
text = JSON.stringify(obj);
console.log(text);
window.onload = function(){
	let dd = document.querySelector('#demo');
	dd.innerHTML = obj.name;
}
</script>
</head>
<body>
	<div id="demo">
	
	</div>
</body>
</html>

JsonController.java

package kr.or.ddit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@RequestMapping("/json")
@Slf4j
@Controller
public class JsonController {
	@GetMapping("/jsonTest01")
	public String jsonTest01(Model model) {
		
		//forwarding : jsp
		return "json/jsonTest01";
	}
	
	@GetMapping("/jsonTest02")
	public String jsonTest02(Model model) {
		
		//forwarding : jsp
		return "json/jsonTest02";
	}
	
	@GetMapping("/jsonTest03")
	public String jsonTest03(Model model) {
		
		//forwarding : jsp
		return "json/jsonTest03";
	}
}

localStorage

  • 웹 브라우저(크롬)에 데이터를 저장
  • 사용자가 브라우저를 닫아도 저장한 데이터를 계속해서 유지할 수 있음
  • key-value 쌍으로 데이터
    • 저장(setItem(key, value))
    • 가져오기(getItem(key))
      key : 저장된 값에 대한 이름
      value : 실제로 저장될 값

jsonTest02.java (localStorage)

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
let myObj, myJSON, text, obj;

window.onload = function(){
	// JSON Object
	myObj = {"name":"아잠만", "type":"먹보", "bir":"2020-06-30"}
	myJSON = JSON.stringify(myObj);
	//웹 브라우저(크롬)에 데이터를 저장
	// 사용자가 브라우저를 닫아도 저장한 데이터를 계속해서 유지할 수 있음
	// key-value 쌍으로 데이터를 저장(setItem(key, value)), 가져오기(getItem(key))
	// key : 저장된 값에 대한 이름
	// value : 실제로 저장될 값
	localStorage.setItem("testJSON", myJSON);
	localStorage.setItem("myObj", myObj);
	text = localStorage.getItem("testJSON");
	obj = JSON.parse(text);
	console.log(obj);
	let str = "<tr>";
		str+="<td>"+obj.name+"</td>";
		str+="<td>"+obj.type+"</td>";
		str+="<td>"+obj.bir+"</td>";
		str+="</tr>";
	document.querySelector('#tbody').innerHTML = str;
}
</script>
</head>
<body>
	<table border="1">
		<thead>
			<tr>
				<th>name</th>
				<th>type</th>
				<th>bir</th>
			</tr>
		</thead>
		<tbody id="tbody">
			
		</tbody>
	</table>
	<div id="demo"></div>
</body>
</html>

jsonTest03.java

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
/*
- JSON은 간단한 데이터 교환 형식임
- JSON은 자체 설명하고 이해하기 쉬움
- JSON은 언어와 무관함
- JSON은 자바스크립트 구문을 사용하지만 형식은 텍스트만 사용함
- 텍스트는 모든 프로그래밍 언어에서 데이터 형식으로 읽고 사용할 수 있음
- 데이터는 이름/값 쌍임
- 데이터는 쉼표로 구분됨
- 중괄호는 객체를 유지함
- 대괄호는 배열을 유지함
- JSON 형식은 자바스크립트 객체와 거의 비슷하며, 단지, JSON에서 키는 문자열이어야
-   하며, 큰 따옴표로 작성해야 하지만, 자바스크립트에서 키는 문자열, 숫자 또는
-   식별자 이름이 될 수 있음
- JSON에서 문자열 값은 큰 따옴표로 작성해야 하지만, 자바스크립트에서는 큰
-   따옴표나 작은 따옴표로 작성할 수 있음
*/
let myObj, x;
window.onload = function(){
	myObj = [
		{"name":"아잠만", "type":"먹보", "species":"오리"},
		{"name":"뽀야미", "type":"친절", "species":"햄스터"},
		{"name":"쭈니", "type":"느끼", "species":"다람쥐"}
		];
	x = myObj.name;
	let str = "";
	myObj.forEach(function(a){
	str+="<tr>";
	str+="<td>"+a.name+"</td>";
	str+="<td>"+a.type+"</td>";
	str+="<td>"+a.species+"</td>";
	str+="</tr>";
	})
document.querySelector('#tbody').innerHTML = str;
}
</script>
</head>
<body>
	<table border="1">
		<thead>
			<tr>
				<th>name</th>
				<th>type</th>
				<th>species</th>
			</tr>
		</thead>
		<tbody id="tbody">
			
		</tbody>
	</table>
	<div id="demo"></div>
</body>
</html>

jsonTest04.java

<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
let myObj, x;
window.onload = function(){
	myObj = [
		{"name":"아잠만", "type":"먹보", "food":{"food1":"사과","food2":"복숭아","food3":"바나나"}},
		{"name":"뽀야미", "type":"친절", "food":{"food1":"오렌지","food2":"딸기","food3":"수박"}},
		];
	x = myObj.name;
	let str = "";
	myObj.forEach(function(a){
	str+="<tr>";
	str+="<td>"+a.name+"</td>";
	str+="<td>"+a.type+"</td>";
	str+="<td>"+a.food.food1+"</td>";
	str+="<td>"+a.food.food2+"</td>";
	str+="<td>"+a.food.food3+"</td>";
	str+="</tr>";
	})
document.querySelector('#tbody').innerHTML = str;
}
</script>
</head>
<body>
	<table border="1">
		<thead>
			<tr>
				<th>name</th>
				<th>type</th>
				<th>과일1</th>
				<th>과일2</th>
				<th>과일3</th>
			</tr>
		</thead>
		<tbody id="tbody">
			
		</tbody>
	</table>
	<div id="demo"></div>
</body>
</html>