因為google前幾頁找不太到如何從網站上抓取.json寫入java中,
故將研究出來的程式碼記錄下來,
以下以Impl實作方法方式編寫,用政府資料開放平台中的登革熱疫情資料作為示範
//從網站上讀出.json檔案的方法
public String readJSON(String url) throws JSONException, IOException {
//new一個stringbulider出來
StringBuilder out = new StringBuilder();
//new一個URL出來,放入url參數
URL website = new URL(url);
URLConnection uc = website.openConnection();
//new一個bufferedreader出來,以匿名物件寫InputStreamReader及getInputStream,註記編碼是UTF-8
BufferedReader br1 = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
//宣告一個字串
String inputline = null;
//當讀入字串不為空時,將內容加入stringbulider中
while ((inputline = br1.readLine()) != null) {
out.append(inputline);
}
br1.close();
return out.toString();
}
//讀出後將.json寫入資料庫的方法
public void addJSON(String json) throws SQLException, JSONException {
//SQL"插入"的語法
sqlstr = "INSERT INTO DengueFever(Year, Month, City, Gender, Age, DiseaseCase) VALUES(?,?,?,?,?,?)";
PreparedStatement state = conn.prepareStatement(sqlstr);
//建立jsonArray
JSONArray jArray = new JSONArray(json);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jArray.get(i);
//sql語法中第一個問號放入"發病年份",因為是字串的jsonObject,故須以Integer.parseInt強制轉型為數字
state.setInt(1, Integer.parseInt((String) jsonObject.get("發病年份")));
state.setInt(2, Integer.parseInt((String) jsonObject.get("發病月份")));
state.setString(3, (String) jsonObject.get("縣市"));
state.setString(4, (String) jsonObject.get("性別"));
state.setString(5, (String) jsonObject.get("年齡層"));
state.setInt(6, Integer.parseInt((String) jsonObject.get("確定病例數")));
state.executeUpdate();
}
System.out.println("AddJSON success.");
state.close();
}
}
以上,同行見笑,
如有任何指教請不吝留言告知,謝謝。
沒有留言:
張貼留言