반응형
1. API결과 json 객체로 변환
StringBuilderresult =new StringBuilder();
try {
String krwStr = "USDKRW"; // default : USDKRW
if (type == 1) {
krwStr = "JPYKRW";
} else if (type == 2) {
krwStr = "EURKRW";
} else if (type == 3) {
krwStr = "CNYKRW";
}
String formatStr = "json"; // default : json
if (format == 1) {
formatStr = "xml";
}
String urlStr = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22" + krwStr + "%22)&format=" + formatStr + "&env=store://datatables.org/alltableswithkeys&callback=";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
stream = conn.getInputStream();
else
stream = conn.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result.toString());
if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get("error") == null) {
JsonObject translatedText = obj.get("query").
getAsJsonObject().
get("results").
getAsJsonObject().
get("rate").
getAsJsonObject();
return translatedText;
}
}
2. gson(json객체)를 map으로 변환
// 환율 정보 가져오기
FinanceXChangeUtil exchange = new FinanceXChangeUtil();
// gson(jsonobject) to map
JsonObject nestedJSON = exchange.getFinanceXChangeValue(0, 0);
Gson gson = new Gson();
LinkedTreeMap result = gson.fromJson(nestedJSON , LinkedTreeMap.class);
// 환율 정보 담기
setAttribute("exchange_rate", result);
※ 야후 API 서비스 종료
반응형
'개발의 흔적 > JAVA' 카테고리의 다른 글
[오류] java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxxMapper (0) | 2018.05.31 |
---|---|
[오류] Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest] (0) | 2018.05.31 |
[spring]Ajax 통신과 일반 통신 비교 (0) | 2018.05.30 |
java, eclipse 환경설정 (0) | 2016.01.22 |
자바 용어 정리 (0) | 2016.01.20 |