[spring] XML 파싱, JSON 파싱 ⭐⭐
by mini_min[spring] XML 파싱, JSON 파싱 ⭐⭐
✔️ XML 파싱, JSON 파싱
: XML 파일이 있다는 가정하에 진행
APISerializer 클래스를 만들어서 공공 API 등의 데이터/XML 과 JSON 문서를 String 형태로 받는 메소드 등을 만든다.
1) String 형태로 받기 : receiveToString
2) 공공 API 등의 XML 데이터를 String 형태의 JSON 으로 변환하여 받기 : receiveXmlToJson
1) String 형태로 받기 : receiveToString
: 긁어 오는 방법이다. (입력 스트림을 사용해서)
String result = null;
HttpURLConnection conn = null;
try {
//긁어오는 방법 - 입력 스트림 써서.
conn = (HttpURLConnection) new URL(spec).openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while ((s = br.readLine()) != null) {
sb.append(s);
}
result = sb.toString();
} catch (Exception e) {
logger.error(e.toString());
throw e;
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception e2) {
}
}
}
return result;
2) 공공 API 등의 XML 데이터를 String 형태의 JSON 으로 변환하여 받기 : receiveXmlToJson
: 주어진 주소 spec 에서 receiveToString 메소드로 XML 을 긁어오고, 해당 XML을 JSON 으로 변환하여 받는다.
String result = null;
try {
String s = receiveToString(spec);
/*
* spec = 주소. 주소에서 receiveToString 메소드로 XML 을 긁어옴
* 아래 코드 필요함.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
*/
JSONObject job = XML.toJSONObject(s);
result = job.toString();
} catch (Exception e) {
// logger.error(e.toString());
throw e;
}
return result;
✔️ XML 문서를 파싱하여 Map에 저장
: XML 문서를 긁어와서 (파싱하여) Map 에 저장하는 메소드이다.
1) 먼저 주소를 읽어들인다. (바이트 스트림으로)
2) InputSource : XML 에 해당되는 내용을 쉽게 파싱할 수 있도록 만들어진 클래스이다.
Map<String, Object> map = new HashMap<>();
InputStream is = null;
try {
List<User> list = new ArrayList<>();
// InputSource : XML 엔티티의 단일 입력 소스
// 먼저 주소 읽어들이기 ! is 는 바이트 스트림.
// 다른점은 InputSource 객체
// InputSource : XML 에 해당되는 내용을 쉽게 파싱할 수 있도록 만들어진 클래스
is = new URL(spec).openConnection().getInputStream();
InputSource source = new InputSource(new InputStreamReader(is, "UTF-8"));
// DOM Document를 생성하기 위하여 팩토리 생성
// 돔을 만들어주는 전 단계가 FACTORY 다.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
// factory.setIgnoringElementContentWhitespace(false);
// 각 태그와 다음 태그의 사이의 공백 및 개행 문자 등을 제거하지 않음
// 팩토리로부터 Document 파서를 얻어내도록 한다.
// 파싱을 할 수 있는 (잘라낼 수 있는) 파서를 얻어낸다.
DocumentBuilder parser = factory.newDocumentBuilder();
// Document DOM 파서로 하여금 입력받은 파일을 파싱하도록 요청한다.
// 아까 소스를 파싱하여 돔을 생성한다.
Document xmlDoc = parser.parse(source);
/*
// InputSource 클래스를 사용하지 않고 commons-io 패키지 IOUtils 클래스사용 하는 경우 (commons-io - 아파치꺼)
is = new URL(spec).openConnection().getInputStream();
is = IOUtils.toInputStream(IOUtils.toString(is, "UTF-8"), "UTF-8");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xmlDoc = parser.parse(is);
*/
// Element : XML 문서의 원소를 표현하기 위해 사용
Element root = xmlDoc.getDocumentElement(); // XML 루트 요소
// 자바스크립트처럼 가져올 때 태그 이름으로 가져옴
// 데이터카운트 의 node 를 가져옴
// 노드의 값을 가져올 때 getFirstChild().getNodeValue();
Node nodeCount = root.getElementsByTagName("dataCount").item(0);
String dataCount = nodeCount.getFirstChild().getNodeValue();
// 여러개의 노드 리스트
NodeList items = root.getElementsByTagName("record");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
//자식들을 또 노트 리스트로 가져오기
NodeList itemList = item.getChildNodes();
// 속성값 가져오기
// 속성값에서 다시 num 값을 찾는다.
// NamedNodeMap itemMap = item.getAttributes(); : 아이템에 들어있는 모든 속성의 모음
NamedNodeMap itemMap = item.getAttributes();
String num = itemMap.getNamedItem("num").getNodeValue();
//itemList : 이름, 값 등의 데이터
User user = new User();
user.setNum(Integer.parseInt(num));
for (int j = 0; j < itemList.getLength(); j++) {
Node e = itemList.item(j);
// 이름, 값 가져오기
if (e.getNodeType() == Node.ELEMENT_NODE) {
String name = e.getNodeName();
String value = e.getChildNodes().item(0).getNodeValue();
//값 넣어주기
if (name.equals("name")) {
user.setName(value);
} else if (name.equals("content")) {
user.setContent(value);
} else if (name.equals("created")) {
user.setCreated(value);
}
}
}
list.add(user);
}
map.put("dataCount", dataCount);
map.put("list", list);
} catch (Exception e) {
System.out.println(e.toString());
} finally {
if (is != null) {
try {
is.close();
} catch (Exception e2) {
}
}
}
return map;
}
'Spring' 카테고리의 다른 글
[spring] 쪽지보내기 , 메일 보내기 Controller,ServiceImpl (0) | 2022.12.05 |
---|---|
[spring] 주간 매출!!!!! 차트 출력하기 (echart) (0) | 2022.12.01 |
[spring] localStorage 사용법! (0) | 2022.11.29 |
[spring] 최근 본 게시글 보기 (0) | 2022.11.29 |
[spring] 파일 처리 / 사진파일 업로드 / 사진 여러개 올리기 (0) | 2022.11.26 |
블로그의 정보
개발자 미니민의 개발로그
mini_min