SpringFramework/Spring

ObjectMapper List 변환

lovineff 2021. 3. 16. 16:39

 

ObjectMapper를 사용하여 List<객체>로 변환하는 방법을 제시한다.

// when
MockHttpServletResponse response = mockMvc.perform(get("/abc/news").accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andReturn()
        .getResponse();

// then
// 방법 1
PoolContent[] poolContents = objectMapper.readValue(response.getContentAsString(), PoolContent[].class);
for(PoolContent poolContent : poolContents){
    System.out.println(poolContent.getTitle());
}

// 방법 2
List<PoolContent> arrayList = Arrays.asList(objectMapper.readValue(response.getContentAsString(), PoolContent[].class));
arrayList.forEach(poolContent -> System.out.println(poolContent.getTitle()));


// 방법 3
List<PoolContent> list = objectMapper.readValue(response.getContentAsString(), new TypeReference<List<PoolContent>>() {});
list.forEach(poolContent -> System.out.println(poolContent.getTitle()));

 

 

'SpringFramework > Spring' 카테고리의 다른 글

AbstractJsonpResponseBodyAdvice Deprecated 대응  (0) 2021.03.19
Spring Vault 연동(datasource 연결 포함)  (0) 2021.03.19
jQuery DataTable Paging Model Mapping  (0) 2021.03.09
Enum 객체 활용 방안  (0) 2021.03.09
Redis 연동  (0) 2020.11.17