약 11분
읽기 설정
글자 크기
줄 간격
글꼴
7.2. JSON 데이터 처리
Java에서는 REST API와의 상호작용시 JSON(JavaScript Object Notation) 형식의 데이터 처리가 필수적입니다. JSON은 웹에서 데이터를 주고받기 위해 설계된 경량 데이터 형식으로, 사람이 읽기 쉬우며 기계가 파싱하고 생성하기 용이합니다. 따라서, JSON 데이터 처리는 백엔드 시스템에서 클라이언트와의 원활한 데이터 통신을 보장합니다.
이제 JSON 데이터를 처리하는 방법에 대해 살펴보겠습니다. JSON을 처리하기 위해 가장 많이 사용하는 라이브러리인 Jackson을 사용할 것입니다. Jackson은 JSON을 자바 객체로 변환하고 자바 객체를 JSON으로 변환하는 작업을 간단하게 처리할 수 있는 라이브러리입니다.
1. JSON 데이터 처리 개요
JSON 데이터 처리의 기본적인 흐름은 다음과 같습니다:
- JSON 문자열을 자바 객체로 변환하기
- 자바 객체를 JSON 문자열로 변환하기
이러한 변환은 주로 아래와 같은 상황에서 필요합니다:
- 사용자 요청을 처리할 때 클라이언트에서 보낸 JSON 데이터를 자바 객체로 변환하여 사용
- 데이터베이스에서 조회한 결과를 JSON 형식으로 클라이언트에 응답하기
2. Gradle에 Jackson 라이브러리 추가하기
먼저 Jackson 라이브러리를 프로젝트에 추가합니다. build.gradle 파일에 다음 의존성을 추가하세요.
dependencies {
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
}
3. Java 객체와 JSON 변환하기
다음은 Java 객체를 JSON으로 변환하는 간단한 예제입니다. Person이라는 클래스를 정의하고 이를 JSON으로 변환해보겠습니다.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
// 객체 생성
Person person = new Person("John", 30);
// ObjectMapper 생성 및 JSON 변환
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(person);
// 출력
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 및 Setter 생략
}
위 코드를 실행하면 다음과 같이 JSON 문자열이 출력됩니다:
{"name":"John","age":30}
이제 JSON 문자열로부터 Java 객체를 생성하는 방법을 살펴보겠습니다.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
String jsonString = "{\"name\":\"John\",\"age\":30}";
// ObjectMapper 생성 및 Java 객체 변환
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
// 출력
System.out.println(person.getName() + " is " + person.getAge() + " years old.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
이 코드는 JSON 문자열을 Person 객체로 변환하여 사용합니다.
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
// 객체 생성
Person person = new Person("John", 30);
// ObjectMapper 생성 및 JSON 변환
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(person);
// 출력
System.out.println(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 및 Setter 생략
}
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) {
try {
String jsonString = "{\"name\":\"John\",\"age\":30}";
// ObjectMapper 생성 및 Java 객체 변환
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
// 출력
System.out.println(person.getName() + " is " + person.getAge() + " years old.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter 및 Setter 생략
}
4. 실습 과제
- JSON 데이터를 활용하여 CRUD를 구현하는 간단한 REST API 서버를 만들어보세요.
- 클라이언트에서 JSON 데이터를 송수신하는 형태로 작업해보세요.
이 과제를 통해 JSON 데이터 처리 및 REST API 기본 개념을 익히고, 나중에 Spring Boot와 결합하여 사용할 수 있는 기초를 다질 수 있습니다.
댓글 0
아직 댓글이 없습니다. 첫 댓글을 남겨보세요.