用 org.json 解析JSON

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         //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 环境变量内。

 

 

 

    

posted @   三岁玩童  阅读(3762)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示