JAVA擷取url中json資料__架構

來源:互聯網
上載者:User
匯入相關的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值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.