<aside> 💡 “{ “키1” : “밸류2”, “키2” : “밸류2”, … “ } ” → JSON 은 키와 밸류로 이뤄짐
</aside>
< 예시 >
index.jsp
<button id="send-get-1">전송</button>
<script>
$("#send-get-1").click(function(){
$.ajax({
url: "${pageContext.servletContext.contextPath}/receive/json",
type: "get",
success: function(data){
console.log(data)
let jsonObject = JSON.parse(data);
// json 형태의 문자열을 javascript의 객체로 변환(파싱)
console.log(jsonObject);
console.log(jsonObject.firstname); //객체의 속성으로 "." 으로 접근
},
error: function(request, status){
alert("code: " + request.status + "\\n"
+ "message: " + request.responseText);
}
});
});
Servlet
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
/* JSON 문자열 만들기 */
String output =
"{\\"type\\":\\"get\\",\\"firstname\\":\\"길동\\",\\"lastname\\":\\"홍\\",\\"age\\":20}";
out.print(output);
out.flush();
out.close();
Servlet에서 파싱 후 화면 내보내기
response.setContentType("application/json; charset=UTF-8");