jaxb xml Unmarshaller

JAVA 2022. 2. 28. 16:37

프로젝트 준비 중 기존 소스에서 내부 api 수신시 xml기반으로 수신을 하게 되어 있어 관련 내용을

소스로 정리 합니다.

jaxb 패키지를 이용해서 unmarshal을 진행 하는 소스 이고 간단한 테스트를 위해 아직 xml로 서비스

하는 공공데이터 포털의 데이터를 이용 합니다.

 

테스트 url은 아래와 같습니다.

https://www.data.go.kr/data/15056803/openapi.do

 

한국공항공사_전국공항 실시간 주차정보

한국공항공사에서 운영하고 있는 전국공항 실시간 주차정보 서비스

www.data.go.kr

해당 데이터를 기준으로 수집을 위해 아래 소스를 작성 했습니다.

package com.unmarshalling;

import java.io.StringReader;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)
@Component
public class AirportParkingInfo  implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		HttpClient client 				= HttpClientBuilder.create().build();
        HttpGet request 				= new HttpGet("http://openapi.airport.co.kr/service/rest/AirportParking/airportparkingRT?serviceKey=");
        
        HttpResponse response 	= client.execute(request);
        HttpEntity entity 				= response.getEntity();
        

        String returnXml 				= EntityUtils.toString(entity, "UTF-8");
        
        System.out.println("returnXml: "+returnXml);
        
        //getter사용하는 경우 counts of IllegalAnnotationExceptions 관련 에러가 발생 될 수 있음
        //@XmlAccessorType 과 관련된 문제 인데 get, set이 필드맵핑과 연결 되기 때문에 변수명이 element명과 같은 경우 동일한 key로 생각 되서 에러가
        //발생됨 테스트 소스 이기 때문에 get없이 변수에 바로 접근
        //get메소드를 만드는 경우 https://code.google.com/archive/p/smw2010-prj3-rest/wikis/JAXBSummary.wiki 참고
        
        JAXBContext jaxbContext 		= JAXBContext .newInstance(XmlResponse.class);
        Unmarshaller unmarshaller 	= jaxbContext.createUnmarshaller();
        
        XmlResponse xmlResponse 	= (XmlResponse)unmarshaller.unmarshal(new StringReader(returnXml));
        
        List<XmlItem> xmlItemList = xmlResponse.bodyInfo().itemsInfo().itemList();
        for(XmlItem tempInfo:xmlItemList) {
        	System.out.println("aprKor: "+tempInfo.aprKor);
        	System.out.println("parkingFullSpace: "+tempInfo.parkingFullSpace);
        }
	}
}

xml element의 구종에 맞춰서 vo를 작성 하면 xml<->object를 자동으로 맵핑 해주기 때문에 아주 편리 합니다.

vo정보는 첨부한 파일을 보면 됩니다.

xml_vo.zip
0.00MB

테스트로 사용한 어노테이션은 2개만 있습니다.

 

@XmlRootElement(name="response") <- 최상위 노드를 지정 합니다.

@XmlElement(name = "body") <- 데이터 맵핑할 노드 정보를 지정 합니다.

복수의 자식 노드들을 지정 하는 경우 

@XmlElement(name = "item")
public List<XmlItem> xmlItemList;

같이 선언 해주는 것으로 맵핑을 해주기 때문에 xml데이터를 가지고 오기 좋습니다.

반응형
Posted by 질주하는구
,