코드의 여백

[웹] JSON 알아보기

by rowing0328

Intro

백엔드 개발자가 매일같이 마주치는 데이터 포맷이다.

 

처음 공부할 땐 단순한 문자열처럼 보이지만,

API를 만들고 다루면서 그 중요성을 실감하게 된다.

 

이 글은 내가 백엔드 공부하면서 JSON을 이해한 과정을 기록한 것이다.

기초 개념, 실전 사용법, 흔한 실수까지 정리해 봤다.

 

 

왜 JSON을 알아야 하는가

백엔드에서 클라이언트와 데이터를 주고받는 가장 일반적인 형식이 JSON이다.


REST API 응답은 거의 예외 없이 JSON이고,
설정 파일도 JSON인 경우가 많다.

 

서버와 프론트 간의 통신, DB 저장, 로그 포맷 등
어디에나 쓰인다.

 

 

JSON의 기본 구조

JSON은 크게 두 가지 기본 구조로 객체배열로 나뉜다.

객체는 키 - 값 쌍으로 구성되고,
배열은 값들의 리스트다.

 

[ JSON 구성요소 정리 ]

타입 예시
문자열 "hello"
숫자 123, 3.14
불린 true, false
null null
객체 {"name": "Jay"}
배열 {"apple", "banana"]

 

 

간단한 API로 응답 다뤄보기 (Java + Spring Boot)

Spring Boot에서 JSON은 자동으로 처리된다.

컨트롤러에서 객체를 리턴하면
Jackson이 내부적으로 이를 JSON으로 직렬화해 준다.

 

[ 모델 클래스 (User.java) ]

@Getter
public class User {
	final private Long id;
    final private String name;
    final private String email;
    
    public User(final id, final String name, final String email) {
    	this.id = id;
        this.name = name;
        this.email = email;
    }
    
    public void setId(final Long id) {
    	this.id = id;
    }
    
    public void setName(final String name) {
    	this.name = name;
    }
    
    public void setEmail(final String email) {
    	this.email = email;
    }
    
}

 

[ 컨트롤러 클래스 (UserController.java) ]

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping
    public User getUser() {
        return new User(1L, "rowing", "dev.hyoseung@gmail.com");
    }
    
}

 

[ 실행 결과 (JSON 응답) ]

{
  "id": 1,
  "name": "rowing",
  "email": "dev.hyoseung@gmail.com"
}

 

 

파싱과 직렬화 (Parsing & Serialization) - Java & Spring Boot

Spring Boot에서는 대부분의 JSON 처리(직렬화와 역직렬화)
Jackson이 자동으로 해준다.


하지만 우리가 직접 JSON 문자열을 객체로 파싱 하거나,

객체를 JSON 문자열로 변환해야 할 때도 있다.

 

[ 객체 -> JSON 문자열 (직렬화) ]

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonExample {
    
	public static void main(String[] args) throws Exception {
        final ObjectMapper objectMapper = new ObjectMapper();

        final User user = new User(1L, "rowing0328", "dev.hyoseung@gmail.com");
        final String json = objectMapper.writeValueAsString(user);

        System.out.println(json);
    }

}

 

[ 출력 ]

{"id":1,"name":"rowing0328","email":"dev.hyoseung@gmail.com"}

 

[ JSON 문자열 -> 객체 (역직렬화) ]

final String json = "{\"id\":1,\"name\":\"rowing0328\",\"email\":\"dev.hyoseung@gmail.com\"}";
final User user = objectMapper.readValue(json, User.class);

System.out.println(user.getName());

 

 

자주 겪는 실수

처음엔 사소한 실수 때문에 파싱이 안 되거나 서버가 500 에러를 뱉는다.

  • 따옴표 실수: JSON은 반드시 더블 쿼트(")를 써야 한다.
  • 쉼표 오류: 마지막 요소 뒤에 쉼표를 두면 오류,
  • 숫자/문자 혼동: "1"(문자)과 1(숫자)은 완전히 다름
  • JSON != JavaScript 객체: JS 객체는 JSON이 아니다.

 

 

마무리

처음에는 JSON이 그냥 텍스트처럼 보였지만,
실제로 API를 만들고 데이터를 주고받아 보니,

이게 개발자 간의 공용 언어라는 걸 알게 됐다.

 

문법이 단순하다고 얕보면 에러에 시달리기 쉽고,

개념을 확실히 잡아두면 어디서든 응용할 수 있다.

 

JSON은 백엔드 개발의 기본 중 기본이다.

정확하게 다룰 수 있는 능력이 쌓이면,

다음 단계인 데이터 모델링이나 API 설계도 훨씬 수월해진다.

 

참고 자료 :

Spring Boot Offical Docs - JSON

 

JSON :: Spring Boot

Auto-configuration for JSON-B is provided. When the JSON-B API and an implementation are on the classpath a Jsonb bean will be automatically configured. The preferred JSON-B implementation is Eclipse Yasson for which dependency management is provided.

docs.spring.io

 

Spring Boot Offical Docs - Jackson JSON 

 

Jackson JSON :: Spring Framework

Spring offers support for the Jackson JSON library.

docs.spring.io

'🌎Web' 카테고리의 다른 글

[웹] '쿠키', '세션', '토큰', 'JWT', 무엇이 다를까?  (0) 2025.05.11

블로그의 정보

코드의 여백

rowing0328

활동하기