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
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 //1 33 String jsonText = jsonObjCreate(); 34 System.out.println("test create object: " + jsonText + "\r\n"); 35 36 //2 37 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 環境變量內。
