심심한잉여의 잡동사니

[파이널 프로젝트] 네이버 검색 API JSON으로 받아 파싱 본문

코딩일기/파이널프로젝트

[파이널 프로젝트] 네이버 검색 API JSON으로 받아 파싱

심심한잉여 2022. 1. 20. 18:27
반응형

원하는 json문자열을 받기위해

GET방식의 URL을 만져서 원하는 요청값으로 만든다.

본인은 100개의 항복을 애견 산책 검색어가 박힌 쇼핑검색으로 했다.

	List<ShoppingVO> resultList = new ArrayList<ShoppingVO>();
		String[] passingSplit = shoppingJson.split("\"items\": \\["); // 앞 잉여데이터 삭제
		passingSplit = passingSplit[1].split("\\]\\}"); // 뒤 잉여데이터 삭제
		passingSplit = passingSplit[0].split("}"); // 각 아이템별로 데이터 나누기
		for (int i = 0; i < passingSplit.length; i++) {
			passingSplit[i] = passingSplit[i].replace(",{", "").replace("{", ""); // 괄호 삭제
		}
		String[][] rowDataArr = new String[passingSplit.length][]; // ROW데이터를 담기위한 2차원 배열
		for (int i = 0; i < passingSplit.length; i++) {
			rowDataArr[i] = passingSplit[i].split("\",\""); // 따움표 삭제
			for (int j = 0; j < rowDataArr[i].length; j++) {
				rowDataArr[i][j] = rowDataArr[i][j].replaceAll("<b>", "").replaceAll("</b>", "") // DB에 담을 값에서 필요 없는
																									// HTML 삭제
						.replaceAll("&quot;", "").strip(); // 필요없는 코드 및 앞 뒤 공백 삭제
			}
		}

		List<Map<String, String>> jsonList = new ArrayList<Map<String, String>>(); // ROW데이터로 분리될 객체MAP을 담을 LIST

		for (int i = 0; i < rowDataArr.length; i++) {
			Map<String, String> shoppingMap = new HashMap<String, String>(); // ROW데이터를 분리할 맵
			for (int j = 0; j < rowDataArr[i].length; j++) {
				String[] rowDataInfo = rowDataArr[i][j].split("\":"); // :로만 나누면 엉뚱하게 나눠지는 내용도 있어 ": 로 스플릿

				shoppingMap.put(rowDataInfo[0].replaceAll("\"", "").strip(), rowDataInfo[1].replaceAll("\"", "").strip()); // 이후
																														// 값에서
																														// 따움표
																														// 삭제
			}
			jsonList.add(shoppingMap); // 아이템별로 MAP값 입력 for문이 돌면서 다시 map을 생성하니 참조ID가 달라서 중복 안됨

		}

		for (int i = 0; i < jsonList.size(); i++) {

			String title = jsonList.get(i).get("title");
			String link = jsonList.get(i).get("link").replaceAll("gate.nhn\\?id\\=", "catalog/"); 
			String image = jsonList.get(i).get("image");
			String lprice = jsonList.get(i).get("lprice");
			String hprice = jsonList.get(i).get("hprice");
			String mallName = jsonList.get(i).get("mallName");
			String productId = jsonList.get(i).get("productId");
			String productType = jsonList.get(i).get("productType");
			String maker = jsonList.get(i).get("maker");
			String brand = jsonList.get(i).get("brand");
			String category1 = jsonList.get(i).get("category1");
			String category2 = jsonList.get(i).get("category2");
			String category3 = jsonList.get(i).get("category3");
			String category4 = jsonList.get(i).get("category4");

			ShoppingVO svo = new ShoppingVO(title, link, image, lprice, hprice, mallName, productId, productType, maker, brand, category1, category2, category3, category4);
		
			resultList.add(svo);
		}
		
		return resultList;

받은 JSON문자열을 가지고 위 코드와 같이 파싱을 했다.

String link = jsonList.get(i).get("link").replaceAll("gate.nhn\\?id\\=", "catalog/");

링크에 맞는 url이 살짝 마음에 들지않아 바로 카탈로그로 갈 수 있도록 살짝 수정하였다.

위 이미지가 기존에 보내지던 링크이며 저 부분만 수정하여 

위 이미지처럼 보이도록 했다.
ID값이 동일하여 문제가 없었다.

파싱은 여기서 마치고

@RequestMapping("/shop/list")
	public String shop(Model model) {
		try {
			model.addAttribute("shopList",shopList);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "/shop/list";
	}

위 코드와 같이 맵핑을 해준 후 JSP로 넘겼다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<c:set var="path" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<c:forEach var="item" items="${shopList}">
	<img alt="썸네일" src="${item.image}" height="300px" width="300px">
	<p><a href="${item.link}">상품명 : ${item.title}</a></p>
	<p>링크 : ${item.link}</p>
	<p>최저가 : ${item.lprice}</p>
	<p>카테고리 1 : ${item.category1}</p>
	<p>카테고리 2 : ${item.category2}</p>
	<p>카테고리 3 : ${item.category3}</p>
	<p>카테고리 4 : ${item.category4}</p>
	
	</c:forEach>
</body>
</html>

view부분은 딱 필요한 정보만 보이도록 하였으며

JSTL을 사용하여 반복문을 실행했다.

 

해당 view를 실행하면 위 이미지와 같으며 정보가 정상적으로 옮겨진 모습을 볼 수 있다.

반응형