JAVA獲取url中json資料
阿新 • • 發佈:2019-02-02
- 匯入相關的jar包
(1)首先感謝 http://m.blog.csdn.net/blog/u013532827/19755907 的分享,我直接使用了 net.sf.json.* 類資料包
(2)資料包的下載地址:http://download.csdn.net/detail/hedgehog8/4237121#comment 裡面的資料包還是比較全的,而且不需要下載積分~
(3)本著儘量少匯入jar包的原則,開始只匯入了json-lib-2.4-jdk15.jar ,報錯:java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeExcept;
(4)網上查了一下,說是還需要匯入
commons-beanutils-1.7.0.jar
commons-lang-2.1.jar
ezmorph-1.0.2.jar
全部匯入後仍報錯,就繼續匯入
commons-collections-3.2.1.jar
commons-logging-1.1.1.jar
然後就可以了~
2.獲取url中的json資料
public static String loadJson (String url) {
StringBuilder json = new StringBuilder();
try {
URL urlObject = new URL(url);
URLConnection uc = urlObject.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
String inputLine = null;
while ( (inputLine = in.readLine()) != null) {
json.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
3 . 根據key獲得value
經過步驟2已經可以獲得json的字串了,下面將根據key值獲得value
String url = " "; //寫上自己的url連結即可,我的就不公佈了哈~
String json = loadJson(url); //獲得json字串
System.out.println(json); //檢測是否正確獲得
JSONObject jsonObject=JSONObject.fromObject(json);
System.out.println(jsonObject.get("id")); //其中id為json中某個key,檢測是否可以獲得value值