본문 바로가기

it-day

JAVA Map안에 배열이 있는데 어떻게 꺼내죠???

 

Map이든 Vo,Dto든

@Data
public class TestVo {

        private HttpStatus status;
        private String message;
        private String errorMessage;
        private Object data;
    }

 

{
   "status":"OK",
   "message":"SUCCESS",
   "errorMessage":null,
   "data":[
      {
         "no":"1",
         "nm":"테스트01",
         "mobileNo":"01000000000",
         "email":"test01@test.co.kr"
      },
      {
         "no":"2",
         "nm":"테스트02",
         "mobileNo":"01000000001",
         "email":"test02@test.co.kr"
      },
   ]
}

 

예를 들어 이렇게 JSON 데이터를

외부 API를 거쳐 objectMapper.readValue를 통해 자바 객체로 받았다 치자

 

"data"의 email의 값만 뽑고 싶다면????

 

// data를 리스트로 
List<Map<String, Object>> mapToList = (List<Map<String, Object>>) result.get("data");

// System.out.println(mapToList);
// [{no=1, nm=테스트01, mobileNo=01000000000, email=test01@test.co.kr}, {no=2, nm=테스트02, mobileNo=01000000001, email=test02@test.co.kr}]

// 리스트를 맵으로
for(Map<String, Object> listToMap :mapToList) {

	// data만 가져와 List로 변환한 데이터를 Map으로 
    System.out.println("@@@@@@@@@@@@@@@@@@"+listToMap);
    //{no=1, nm=테스트01, mobileNo=01000000000, email=test01@test.co.kr}
    //{no=2, nm=테스트02, mobileNo=01000000001, email=test02@test.co.kr}
    
    // Map의 특정 key값의 데이터만 뽑기
    System.out.println(listToMap.get("email"));
    // test01@test.co.kr
    // test02@test.co.kr
}