java中JSONObject與JSONArray的使用


JSONObject與JSONArray

最近在學習過程中用到了稍微復雜點的json數據需要將json數據解析出來,這里就截取一部分作為例子

1.JSONObject介紹

JSONObject-lib包是一個beans,collections,maps,java arrays和xml和JSON互相轉換的包。

2.下載jar包

http://files.cnblogs.com/java-pan/lib.rar

 

*或者在Maven的pom.xml文件中直接配置如下:

<dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
</dependency>

 

 json數據:

{
    "cartypes":[
        {"id":1,"imgUrl":"img/l.jpg","bigimg": "img/d.jpg","title":"別克威朗","marketprice":"15.29","periods":"12",
           "endrepayone":"96800","endrepaytwo":"96800","endrepaythree":"93000",
           "endmonthone":"3408","endmonthtwo":"3408","endmonththree":"3278",
           "repayfirst":"15290","repaytwo":"22935", "repaythree":"30580",
           "monthrepayone":"3578","monthrepaytwo":"2878","monthrepaythree":"2478",
           "cardetails": 
[{
"imageId00": "img/first-bkwl.jpg", "imageId01": "img/bkwl01.jpg", "imageId02": "img/bkwl02.jpg", "imageId03": "img/bkwl03.jpg", "imageId04": "img/bkwl04.jpg", "carname": "別克", "carmatter": "威朗", "carvolume":"1.5L", "sitnum":"5", "cargearbox":"6擋手自一體", "caremission":"國V", "carldone":"一體式座艙", "carldtwo":"絨面內飾", "carldthree":"全景天窗", "carldfour":"展翼型HID大燈" }] }, {"id":2,"imgUrl":"img/l.jpg","bigimg": "img/d.jpg","title":"英菲尼迪","marketprice":"18.98","periods":"12", "endrepayone":"126800","endrepaytwo":"126800","endrepaythree":"126800", "endmonthone":"4458","endmonthtwo":"4458","endmonththree":"4458", "repayfirst":"18980","repaytwo":"28470", "repaythree":"37960", "monthrepayone":"2738","monthrepaytwo":"1878","monthrepaythree":"998", "cardetails":
[{
"imageId00": "img/first.jpg", "imageId01": "img/yfnd01.jpg", "imageId02": "img/yfnd02.jpg", "imageId03": "img/yfnd03.jpg", "imageId04": "img/yfnd04.jpg", "carname": "英菲尼迪", "carmatter": "ESQ", "carvolume":"1.6L", "sitnum":"5", "cargearbox":"CVT無級變速", "caremission":"國V", "carldone":"定制輪轂", "carldtwo":"多功能方向盤", "carldthree":"LED尾燈", "carldfour":"真皮座椅" }]
}
] }

當接受到的是上面的json數據時,要獲取到里面的鍵對應的值應該怎樣做呢,比如要獲取title的值,獲取cardetails中的imageId02的值等。


面對這樣數組與對象相互嵌套的情況需要一步步將數據拆分,主要思想還是根據鍵取值,對於數組類型還是需要先根據”下標”取出元素。這里還需要用到JSONObject與JSONArray。

 

將上面的json數據簡化就是:(這里保留個id便於識別)

{
    "cartypes":[
              {
                 "id":1,"bigimg": "img/dt-bkwl.jpg",
                 "cardetails": [{ "imageId02": "img/bkwl02.jpg}]
               }

{
          "id":2,"bigimg": "img/xxx.jpg",
          "cardetails":[{"imageId002":"img/xx.jpg"}]
}          ] }

這就是簡化了的json數據,可以看出這個串最外層是一個大的鍵為cartypes的對象,而它的值是json數組形式的比較復雜的json數據。繼續分析 [ ]的部分,可以看到,里面有兩個數組元素,每個元素分別是被{ }包起來的json對象,他們的元素組成相同,再看每個元素里面包含幾個鍵值對的數據,其中鍵cardetails的值又是一個嵌套的json數組,里面包含一個json對象。分析完畢。那該怎樣才能(拿到數據)解析呢?

 使用JSONObject與JSONArray

一般取數據有兩種方式,看需要選擇。

方式①:

通過 JSONObject.getString("鍵")直接獲取,這種方式只能每次獲取一個。

 方式②

通過構建與json對象相應的bean來獲取。

 

我在寫上面的例子時用到了兩種方式,由於需要使用到 id,bigimg以及cardetails中的大部分數據,因此我在使用時將cardetails封裝成一個bean,方便使用,而其他用到的比較少,因此就直接根據鍵獲取值。

另外需要注意的是,JSONObject,JSONArray分別對應的是json數據的兩種格式。即{"張三" : "男"}  , [{ 張三" : " 男" }] ,使用時需要將其轉換成對應的對象。

如(示例):

JSONObject jsonObject = JSONObject.fromObject(json);   //將json字符串轉換為JSONObject
JSONArray jsonArray = JSONArray.fromObject(json);  //將json字符串轉換為JSONArray

還有一點需要指出:在取鍵值是始終需要根據鍵取值,從外到內,取內層的鍵的值需要先獲取外層鍵的值,如果跨越取值會報錯。

下面演示取值:

JSONObject jsonObject = JSONObject.fromObject(json);   //將json字符串轉化為JSONObject
String cartypes=jsonObject.getString("cartypes");      //通過getString("cartypes")取出里面的信息
JSONArray jsonArray = JSONArray.fromObject(cartypes);  //將取到的cartypes對應的(一組)值字符串轉換為JSONArray
String id= job.getString("id"); //取id String bigImg = job.getString("bigimg"); //大圖
System.out.println("bigImg:"+bigImg); //可以顯示已經拿到bigimg的值

 

由於cardetails下的基本都是需要的值,一個一個取值比較麻煩,因此將cardetails封裝成一個bean  如下:

Cardetails.java

public class Cardetails {
    private String imageId00;
    private String imageId01;
    private String imageId02;
    private String imageId03;
    private String imageId04;
    private String carname;
    private String carmatter;
    private String carvolume;
    private int sitnum;
    private String cargearbox;
    private String  caremission;
    private String carldone;
    private String carldtwo;
    private String carldthree;
    private String carldfour;
    //get set 方法以及toString方法略
}

 

到這里,需要將cardetails中的鍵全轉成Cardetails中的屬性,方法如下:

//將cardetail封裝成bean
JSONArray carDetailArr=job.getJSONArray("cardetails");//將json字符串轉化為JSONArray JSONObject carDetailObj = carDetailArr.getJSONObject(0);//獲取數組第一個元素 Cardetails cardetails = (Cardetails) JSONObject.toBean(carDetailObj, Cardetails.class);//封裝成bean
System.out.println("cardetails:"+cardetails); //能獲取到數據


最后附上部分代碼:

public void getICarDetail(int id){
        String json=null;
        try {
             json=iCarDetail.getICarDetail(id);//這里既是獲取上面json數據
        } catch (Exception e) {
            e.printStackTrace();
        }
        int jsonId=0;//json數組里的id值
        JSONObject jsonObject = JSONObject.fromObject(json);   //將json字符串轉化為JSONObject
        String cartypes=jsonObject.getString("cartypes");//通過getString("cartypes")取出里面的信息
        JSONArray jsonArray = JSONArray.fromObject(cartypes);  //將取到的cartypes對應的(一組)值字符串轉換為JSONArray
        //遍歷jsonarray 數組
        if(jsonArray.size()>0){
            for(int i=0;i<jsonArray.size();i++){
                JSONObject job = jsonArray.getJSONObject(i);//把每一個對象轉成json對象
                jsonId=(int)job.get("id"); //得到每個對象中的id值
                if(jsonId==id){
                    //獲取相關值
                    String title = job.getString("title");            
                    String bigImg = job.getString("bigimg");          
                    String repayFirst = job.getString("repayfirst");  
                    String endrepayone = job.getString("endrepayone");
                    String endmonthone = job.getString("endmonthone");
                    String marketprice = job.getString("marketprice");
//將cardetail封裝成bean JSONArray carDetailArr=job.getJSONArray("cardetails");//將json字符串轉化為JSONArray JSONObject carDetailObj = carDetailArr.getJSONObject(0);//獲取數組第一個元素 Cardetails cardetails = (Cardetails) JSONObject.toBean(carDetailObj, Cardetails.class);//封裝成bean //輸出顯示 System.out.println("******************"); System.out.println("jsonId:"+jsonId); System.out.println("title:"+title); System.out.println("bigImg:"+bigImg); System.out.println("repayFirst:"+repayFirst); System.out.println("endrepayone:"+endrepayone); System.out.println("endmonthone:"+endmonthone); System.out.println("marketprice:"+marketprice); System.out.println("cardetails:"+cardetails);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM