Development

@requestbody를 사용하여 양식 데이터를 JSON 문자열로 변환하는 방법.

sonpro 2023. 3. 9. 16:45
반응형

Convert

How to Convert Form Data to JSON String with @RequestBody

In modern web development, it is common to send data between the client and server using JSON. However, sometimes you may need to receive form data from the client and convert it into a JSON string on the server-side. This is where the @RequestBody annotation comes in handy. In this blog post, we will explore how to use @RequestBody to convert form data to a JSON string.

What is @RequestBody?

@RequestBody is an annotation in Spring Boot that binds the HTTP request body to a Java object. It is commonly used to receive JSON or XML data from the client and convert it into a Java object. However, it can also be used to receive form data and convert it into a JSON string.

How to Use @RequestBody to Convert Form Data to JSON String

To use @RequestBody to convert form data to a JSON string, you need to follow these steps:

  1. Create a Java class that represents the form data.
  2. Add the @RequestBody annotation to the method parameter that will receive the form data.
  3. Convert the Java object to a JSON string using a JSON library.

Here is an example of how to use @RequestBody to convert form data to a JSON string:

@PostMapping("/submit-form")
public String submitForm(@RequestBody FormData formData) {
    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(formData);
    return json;
}

In this example, we have a @PostMapping method that receives form data using the @RequestBody annotation. The FormData class represents the form data and is automatically populated by Spring Boot using the form data sent by the client. We then use the Jackson JSON library to convert the FormData object to a JSON string.

Conclusion

In conclusion, @RequestBody is a powerful annotation in Spring Boot that can be used to receive form data and convert it into a JSON string. By following the steps outlined in this blog post, you can easily convert form data to a JSON string on the server-side. This can be useful in situations where you need to send the form data to an API or store it in a database.

반응형