Open API 요청 시 데이터는 XML 또는 JSON으로 반환된다. 지금 사용하는 데이터는 XML 형식으로 받을 수 있다.
이를 애플리케이션에서 사용할 객체로 변환하기 위해서는 파싱을 해야하며, 비교적 사용이 쉬운 DOM
파서를 이용하였다.
이전 포스트에서 OpenAPI에 공연 정보 데이터 요청 후 데이터를 그대로 응답하는 API를 만들었었다. 이를 이용하여 공연 객체 리스트를 JSON 형식으로 반환하는 API를 만들 것이다.
Show
엔티티 클래스를 작성하였다.@Builder
@Getter
public class Show {
private String showId; //공연ID PF132236
private String showName;//공연명 우리연애할까
private LocalDate startDate; //공연시작일 2016.05.12
private LocalDate endDate;//공연종료일 2016.07.31
private String hallName; //공연시설(공연장명) 피가로아트홀(구 훈아트홀)
private String posterUrl;//포스터이미지경로 http://www.kopis.or.kr/upload/pfmPoster/PF_PF132236_160704_142630.gif
private String status;//공연상태
private boolean openRun;//오픈런
}
@Component
public class XmlParser {
final private DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
public Show getShow(InputStream in) {
try {
// API의 XML 문서 Document 인스턴스에 저장
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = (Document) documentBuilder.parse(new InputSource(in));
//Dom Tree를 XML 문서의 구조대로 만들기
document.getDocumentElement().normalize();
//<db>태그를 하나씩 Map에 담고, 이들을 리스트에 담는다.
List<Map> mapList = new ArrayList<>();
int itemLen = document.getElementsByTagName("db").getLength();
for (int i = 0; i < itemLen; i++) {
Node firstNode = document.getElementsByTagName("db").item(i);
NodeList childNodeList = firstNode.getChildNodes();
Map<String, Object> nodeMapData = getNodeList(childNodeList);
mapList.add(nodeMapData);
}
System.out.println(mapList);
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
public static Map<String, Object> getNodeList(NodeList nodeList) {
Map<String, Object> dataMap = new HashMap<>();
for (int i = 0; i < nodeList.getLength(); i++) {
String tagName = nodeList.item(i).getNodeName();
if (!"#text".equals(tagName)) {
if (nodeList.item(i).getChildNodes().getLength() > 1) {
dataMap.put(tagName, getNodeList(nodeList.item(i).getChildNodes()));
} else {
dataMap.put(tagName, nodeList.item(i).getTextContent());
}
}
}
return dataMap;
}
}