SW-PRODUCT/개발

Jackson 활용기...

굴돌 2015. 7. 22. 21:47



@JsonView를 사용하려면 mapper에 몇가지 설정을 해줘야한다.


    @Test
    public void testQuery() throws JsonProcessingException {
        UserId userId = new UserId(1L);
        QueryParam step1 = new QueryParam( SandboxFriends.LABEL, 0, 1, Direction.out.name());
        GetEdgesResponse<SandboxFriends> ret = helper.getEdges(userId, new TypeReference<GetEdgesResponse<SandboxFriends>>(){}, new QueryStep( step1 ));
       
        logger.debug( ret.toString() );
       
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
       
        System.out.println( mapper.writerWithView( Edge.Insert.class ).writeValueAsString( ret.getResults().get(0) ) );
    }



Java에는 Type-erasure라는 것이 있단다.

Runtime에 Generic variable로 남아있는 것들은 모두 Object로 바뀐단다...

이때문에 json deserialization 할 때 type 정보가 사라져서 HashMap으로 대체되는 일이 발생한다.


이를 극복하려면 아래처럼 TypeReference를 caller가 지정해서 generic 변수를 compile 타임에 지정해줘야 한다.


GetEdgesResponse<SandboxFriends> ret = helper.getEdges(userId, new TypeReference<GetEdgesResponse<SandboxFriends>>(){}, new QueryStep( step1 ));