개발/spring

gson으로 spring에서 http 객체 파싱하기

소확행개발자 2018. 10. 5. 13:33

gson으로 spring에서 http 객체 파싱하기

gson 

jackson과 gson 모두 java에서 지원하는 json 데이타를 바인딩하는 라이브러리이다. 둘다 오픈소스 프로젝트이고 다양한 제네릭 자바 타입을 지원한다.

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

ActorGson rudyYoungblood = new ActorGson(
"nm2199632",
sdf.parse("21-09-1982"),
Arrays.asList("Apocalypto",
"Beatdown", "Wind Walkers")
);
Movie movie = new Movie(
"tt0472043",
"Mel Gibson",
Arrays.asList(rudyYoungblood));

String serializedMovie = new Gson().toJson(movie);
코드는 copy Jackson vs Gson baeldung url : https://www.baeldung.com/jackson-vs-gson 

{
    "imdbId": "tt0472043",
    "director": "Mel Gibson",
    "actors": [{
        "imdbId": "nm2199632",
        "dateOfBirth": "Sep 21, 1982 12:00:00 AM",
        "filmography": ["Apocalypto", "Beatdown", "Wind Walkers"]
    }]
}

entity의 데이터는 null값이 아니기때문에 모두 나열되고
dateOfBirth는 gson date pattern으로 translated 된다.
output 은 지정되어있지 않고 json propertie는 java의 entity에 의해서 나열된다. 

spring에서 http 객체 파싱하기

gson 은 자바 라이브러리 기반으로 REST end point 를 @Controller로 등록한 다음에 객체를 jsonArray 로 바꿀 수 있는데, spring boot 와 java config 그리고 xml 로 config option을 정할 수 있다.

spring 에서 object 를 어떻게 json으로 변환시키는지 이해하는게 중요한데 전형적인 spring mvc 에서 요청이 @controller를 나갈 경우 렌더링할 뷰를 찾는다.

@RequestBody 나 @RestController 로 지정할때 요청은 단계를 지나서 spring 요청을 하고 모델의 자바 객체를 응답에 직접 작성한다.

spring은 그러면서 HttpMessageConverter 를 찾는다. 우리의 경우엔 mime type json을 찾을 텐데 spring configures 에는 기본적으로
MappingJackson2HttpMessageConverter 가 있다. 그래서 이를 gson 의 GsonHttpMessageConverter를 이용해서 변경하면 된다.

    Jackson exclude

jackson의 autoconfig를 제거하지 않으면 충돌이 나기 때문에 이를 빼주어야 하는데 이는

application.class 에서

@SpringBootApplication
@EnableAutoConfiguration(exclude = { JacksonAutoConfiguration.class })
public class OVNDApplication {
public static void main(String[] args) {
SpringApplication.run(OVNDApplication.class, args);
}
}
를 해주면 된다.
/**
* 1. 방법 jackson을 exclude 했을 경우.
*/

@Bean
public GsonHttpMessageConverter gsonHttpMessageConverter() {
final GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setGson(MapperUtil.getGsonInstance());
return converter;
}


/**
* 2. 방법 HttpMessageConvertes로 configure 를 추가하면 기존 config보다 앞에 선언되기 때문에
* jackson보다 우선 config 된다.
*/
@Bean
public HttpMessageConverters customConverter() {
Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
GsonHttpMessageConverter gsonHttpMessageConverter = new GsonHttpMessageConverter();
messageConverters.add(gsonHttpMessageConverter);
return new HttpMessageConverters(true, messageConverters);
}