Java Serialization & Unserialization

박진석·2025년 2월 3일
0
post-thumbnail

How does Java objects and JSON work together in HTTP communication????

The Basic Problem: Speaking Different Languages

Imagine we have two friends who speak different languages trying to communicate. HTTP speaks the language of JSON, while Java speaks the language of objects. They need a translator to understand each other!

What is Serialization in This Context?

Serialization is like translating from "Java language" to "JSON language."

Article article = new Article("제목", "내용");

// When serialized to JSON, it becomes:
{
    "title": "제목",
    "content": "내용"
}

This happens in our code when our Spring controller sends a response. For example, in our BlogApiController, when you return an Article, Spring automatically serializes it to JSON:

@PostMapping("/api/articles")
public ResponseEntity<Article> addArticle(@RequestBody AddArticleRequest request) {
    Article savedArticle = blogService.save(request);  // This is a Java object
    return ResponseEntity.status(HttpStatus.CREATED)
            .body(savedArticle);  // Spring converts it to JSON here!
}

What is Deserialization in This Context?

Deserialization is like translating from "JSON language" back to "Java language." When our API receives a JSON request, it needs to turn it into a Java object that our code can work with.

This happens with the @RequestBody annotation:

// Incoming JSON:
{
    "title": "제목",
    "content": "내용"
}

// Gets deserialized into your AddArticleRequest object:
AddArticleRequest request = new AddArticleRequest("제목", "내용");

How Spring Makes This Easy

Spring handles all this translation automatically:

  1. When a request comes in with JSON data, Spring sees the @RequestBody annotation and knows it needs to deserialize the JSON into your AddArticleRequest class.

  2. When we return an Article object, Spring knows it needs to serialize it back into JSON before sending the HTTP response.

Our AddArticleRequest class is designed to support this:

@NoArgsConstructor  // Needed for deserialization
@AllArgsConstructor
@Getter
public class AddArticleRequest {
    private String title;
    private String content;
    // ...
}

The annotations help Spring know how to map the JSON fields to our Java object properties. It's like having a really smart translator that knows exactly how to convert between the two formats! 😊

This is why modern web applications are so powerful - they can seamlessly handle communication between different systems that speak different "languages." 😊😊😊

0개의 댓글