用 org.json 解析JSON

來源:互聯網
上載者:User

標籤:tde   sans   git   return   and   classpath   jpa   tle   jason   

1.下載 java-json.jar 包

    介紹:http://www.json.org/

    下載:

            https://github.com/stleary/JSON-java/releases

            https://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22org.json%22%20AND%20a%3A%22json%22

           附件:java-json.jar.zip

           附件:json-20160810-javadoc.jar      

 

2.解析 JSON 

    代碼如下:

 1 import org.json.JSONObject; 2 import org.json.JSONException;  3  4 public class testJson{ 5      6     public static String jsonObjCreate(){ 7         JSONObject jsonObj = new JSONObject();   8         try {   9             jsonObj.put("name", "Jason");  10             jsonObj.put("id", 20130001);  11             jsonObj.put("phone", "13579246810");              12             13             return jsonObj.toString();14             15         } catch (JSONException e) {  16             e.printStackTrace();  17         }18         return null;          19     }20     21     public static void jsonObjParse(String jsonText) {22         try{23             JSONObject jsonObj = new JSONObject(jsonText);24             System.out.println("test parse name: " + jsonObj.getString("name"));25             System.out.println("test parse id  : " +jsonObj.getInt("id"));26         } catch (JSONException e) {  27             e.printStackTrace();  28         } 29     }30 31     public static void main(String[] args){        32         //133         String jsonText = jsonObjCreate();34         System.out.println("test create object: " + jsonText + "\r\n");35         36         //237         jsonObjParse(jsonText);38     }39 }

3.執行結果:

    

4.遇到的問題:

    (1)

        testJson.java:23: 錯誤: 未報告的異常錯誤JSONException; 必須對其進行捕獲或聲明以便拋出

        JSONObject jsonObj = new JSONObject(jsonText);

        解決:加try catch

    (2) 編譯過但執行報錯

        Error: A JNI error has occurred, please check your installation and try again Exception in thread "main" java.lang.NoClassDefFoundError:                 org/json/JSONException         at java.lang.Class.getDeclaredMethods0(Native Method)

        解決:將 java-json.jar 加到 CLASSPATH 環境變數內。

 

 

 

    

用 org.json 解析JSON

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.