Programming/SpringBoot

[Spring] Spring에서 JSON 파라미터를 Java객체로 받기

owls 2024. 5. 27. 15:10
728x90

Spring에서 Request,Response로 전달되는 파라미터 정보를 컨트롤러에서 어떻게 Java객체로 받을까?

Spring에서 HttpMessageConvert가 그 역할을 담당하고 있다.

Request, Response내에는 모두 text형식이라고 할 수 있다. 이를 Java자료형으로 변환해주는 역할을 한다.

 

HttpMessageConvert

  • ByteArrayHttpMessageConvert
  • StringHttpMessageConvert
  • FormHttpMessageConvert
  • SourceHttpMessageConvert
  • Jax2RootElementHttpMessageConvert
  • MarshallingHttpMessageConvert
  • MappingJackson2HttpMessageConverter
  • ....

이외에도 Spring은 많은 MessageConverter를 지원한다.

 

MappingJackson2HttpMessageConverter는 JSON형태의 데이터를 POJO객체로 변환하는 역할을 담당한다.

생성자에서 Jackson라이브러리의 ObjectMapper클래스를 생성해서 가지고 있다.(build 메서드)

이를 이용해서 JSON을 객체로 변환하는 것이다.

public class MappingJackson2HttpMessageConverter extends AbstractJackson2HttpMessageConverter {

    private String jsonPrefix;

    public MappingJackson2HttpMessageConverter() {
        this(Jackson2ObjectMapperBuilder.json().build());
    }

    public MappingJackson2HttpMessageConverter(ObjectMapper objectMapper) {
        super(objectMapper, new MediaType[]{MediaType.APPLICATION_JSON_UTF8, new MediaType("application", "*+json", DEFAULT_CHARSET)});
    }

    public void setJsonPrefix(String jsonPrefix) {
        this.jsonPrefix = jsonPrefix;
    }

    public void setPrefixJson(boolean prefixJson) {
        this.jsonPrefix = prefixJson ? ")]}', " : null;
    }

    protected void writePrefix(JsonGenerator generator, Object object) throws IOException {
        if (this.jsonPrefix != null) {
            generator.writeRaw(this.jsonPrefix);
        }

        String jsonpFunction = object instanceof MappingJacksonValue ? ((MappingJacksonValue)object).getJsonpFunction() : null;
        
        if (jsonpFunction != null) {
            generator.writeRaw("/**/");
            generator.writeRaw(jsonpFunction + "(");
        }
    }

    protected void writeSuffix(JsonGenerator generator, Object object) throws IOException {
        String jsonpFunction = object instanceof MappingJacksonValue ? ((MappingJacksonValue)object).getJsonpFunction() : null;

        if (jsonpFunction != null) {
            generator.writeRaw(");");
        }
    }
}
 

MappingJackson2HttpMessageConverter (Spring Framework 6.1.8 API)

Indicate whether the JSON output by this view should be prefixed with ")]}', ". Default is false. Prefixing the JSON string in this manner is used to help prevent JSON Hijacking. The prefix renders the string syntactically invalid as a script so that it ca

docs.spring.io

 

 

변환 Converter 클래스들은 AbstractJackson2HttpMessageConverter 추상 클래스를 상속받아 구현되었다.

 

 

 

 

 

 

 

참고

 

 

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html

 

 

 

 

728x90