inblog logo
|
DailyCoding
    Network & Socket

    4. JSON(JavaScript Object Notation)

    박은서's avatar
    박은서
    Feb 09, 2026
    4. JSON(JavaScript Object Notation)
    Contents
    1. JSON(JavaScript Object Notation)1️⃣ JSON이란?2️⃣ JSON의 필요성3️⃣ JSON 설정 방법4️⃣ 실습

    1. JSON(JavaScript Object Notation)

    1️⃣ JSON이란?

    데이터를 주고받기 위한 텍스트 기반 데이터 형식
    소켓, HTTP, REST API에서 가장 많이 쓰이는 데이터 포맷 중 하나
    ➡️ JSON은 사람이 읽기 쉽고, 기계가 파싱하기 쉬운 데이터 표현 방식

    2️⃣ JSON의 필요성

    • 언어 독립적 (Java, JS, Python 다 가능)
    • 가볍고 단순
    • 네트워크 통신에 적합
    • 구조화된 데이터 표현 가능
    ➡️ 통신용 공용 언어

    3️⃣ JSON 설정 방법

    notion image
    notion image
    notion image
    notion image
    복사 붙여넣기 → 주석 삭제 → 코끼리 아이콘 클릭
    복사 붙여넣기 → 주석 삭제 → 코끼리 아이콘 클릭

    4️⃣ 실습

    1) Server

    package com.mtcoding.ex06; import com.google.gson.Gson; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class MyServer4 { public static void main(String[] args) { try { ServerSocket ss = new ServerSocket(20000); Socket socket = ss.accept(); // 읽기 버퍼 Scanner sc = new Scanner(socket.getInputStream()); // 쓰기 버퍼 PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); while (true) { String line = sc.nextLine(); // 엔터키(\n)까지 읽기 / 엔터키까지 안읽는 다른 함수도 있음 Gson gson = new Gson(); Person p = gson.fromJson(line, Person.class); System.out.println(p.getNo()); System.out.println(p.getName()); System.out.println(p.getAge()); System.out.println(p.getHobby().get(0)); System.out.println(p.getHobby().get(1)); pw.println("ok"); } } catch (Exception e) { e.printStackTrace(); } } }

    2) Client

    package com.mtcoding.ex06; import com.google.gson.Gson; import java.io.PrintWriter; import java.net.Socket; import java.util.Arrays; import java.util.Scanner; public class MyClient4 { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1", 20000); // 자기 자신 IP 주소 - 127.0.0.1 or localhost PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); // 쓰기 버퍼 / true -> autoflush Scanner socketSc = new Scanner(socket.getInputStream()); Person person = new Person(1, "홍길동", 20, Arrays.asList("축구", "농구")); Gson gson = new Gson(); String json = gson.toJson(person); pw.println(json); // ln이 \n이 넣어주고, autoFlush가 된다. String recv = socketSc.nextLine(); System.out.println("서버로부터 받은 메시지 : " + recv); } catch (Exception e) { e.printStackTrace(); } } }

    3) Server 결과

    notion image

    4) Client 결과

    notion image
    Share article
    Contents
    1. JSON(JavaScript Object Notation)1️⃣ JSON이란?2️⃣ JSON의 필요성3️⃣ JSON 설정 방법4️⃣ 실습

    DailyCoding

    RSS·Powered by Inblog