java中JSONObject与JSONArray的使用

JSONObject与JSONArray

最近在学习过程中用到了稍微复杂点的json数据需要将json数据解析出来,这里就截取一部分作为例子

1.JSONObject介绍

JSONObject-lib包是一个beans,collections,maps,java arrays和xml和JSON互相转换的包。

2.下载jar包

https://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);
}

 

posted on 2017-11-28 15:51  风的形状  阅读(65091)  评论(1编辑  收藏  举报