반응형
Spring Boot에서 JSON 데이터를 보내고 받는 방법
Spring Boot는 RESTful 웹 서비스를 구축할 때 JSON 데이터를 주고받는 작업을 매우 간단하게 처리할 수 있도록 지원합니다. 이 글에서는 JSON 데이터를 처리하기 위한 기본적인 방법과 사용 예제를 설명합니다.
1. JSON이란?
JSON(JavaScript Object Notation)은 데이터를 저장하고 전송하는 데 사용되는 경량 데이터 형식입니다.
예시:
{
"id": 1,
"name": "John Doe",
"email": "john.doe@example.com"
}
JSON은 키-값 쌍으로 구성되어 있으며, Spring Boot에서는 이를 Java 객체로 쉽게 변환하고, 반대로도 가능합니다.
2. Spring Boot 프로젝트 설정
Spring Boot에서 JSON 처리를 위해 필요한 의존성은 기본적으로 포함되어 있습니다. 만약 Maven 프로젝트를 사용한다면, 다음과 같은 의존성이 필요합니다:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradle 사용 시:
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
}
3. JSON 데이터 보내기 (POST 요청)
예제: 클라이언트에서 서버로 JSON 데이터를 전송하여 새로운 사용자 정보를 생성하는 API
Step 1: 컨트롤러 작성
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody User user) {
return "사용자가 생성되었습니다: " + user.getName();
}
}
class User {
private Long id;
private String name;
private String email;
// Getter와 Setter
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Step 2: Postman으로 테스트
- Method:
POST
- URL:
http://localhost:8080/api/users
- Body:
{ "id": 1, "name": "John Doe", "email": "john.doe@example.com" }
- 결과:
사용자가 생성되었습니다: John Doe
4. JSON 데이터 받기 (GET 요청)
예제: 서버에서 JSON 데이터를 반환하는 API
Step 1: 컨트롤러 작성
import org.springframework.web.bind.annotation.*;
import java.util.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> getAllUsers() {
List<User> users = new ArrayList<>();
users.add(new User(1L, "John Doe", "john.doe@example.com"));
users.add(new User(2L, "Jane Doe", "jane.doe@example.com"));
return users;
}
}
class User {
private Long id;
private String name;
private String email;
public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getter와 Setter 생략
}
Step 2: Postman으로 테스트
- Method:
GET
- URL:
http://localhost:8080/api/users
- 결과:
[ { "id": 1, "name": "John Doe", "email": "john.doe@example.com" }, { "id": 2, "name": "Jane Doe", "email": "jane.doe@example.com" } ]
5. JSON 데이터 수정하기 (PUT 요청)
예제: 특정 사용자의 정보를 수정하는 API
@PutMapping("/{id}")
public String updateUser(@PathVariable Long id, @RequestBody User user) {
return "ID가 " + id + "인 사용자의 정보가 수정되었습니다: " + user.getName();
}
Postman 테스트
- Method:
PUT
- URL:
http://localhost:8080/api/users/1
- Body:
{ "name": "Updated Name", "email": "updated.email@example.com" }
- 결과:
ID가 1인 사용자의 정보가 수정되었습니다: Updated Name
6. JSON 데이터 삭제하기 (DELETE 요청)
예제: 특정 사용자를 삭제하는 API
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
return "ID가 " + id + "인 사용자가 삭제되었습니다.";
}
Postman 테스트
- Method:
DELETE
- URL:
http://localhost:8080/api/users/1
- 결과:
ID가 1인 사용자가 삭제되었습니다.
반응형
'Spring Boot' 카테고리의 다른 글
Spring Boot에서 API 문서를 작성하는 쉬운 방법: Swagger (0) | 2025.01.08 |
---|---|
Spring Boot에서 데이터 유효성(Validation) 검사를 적용하는 방법 (0) | 2025.01.08 |
Spring Boot에서 application.yml 파일을 설정하는 방법 (0) | 2025.01.08 |
Postman으로 Spring Boot API를 테스트하는 방법 (0) | 2025.01.08 |
Spring Boot API Server 개발에서 GET / POST / PUT / DELETE 요청 처리하는 방법 (0) | 2025.01.08 |