好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java JSONObject与JSONArray对象案例详解

JSONObject与JSONArray

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

1.JSONObject介绍

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

2.下载jar包

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

?

1

2

3

4

5

6

< dependency >

             < groupId >net.sf.json-lib</ groupId >

             < artifactId >json-lib</ artifactId >

             < version >2.4</ version >

             < classifier >jdk15</ classifier >

</ dependency >

json数据:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

{

     "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便于识别)

?

1

2

3

4

5

6

7

8

{

     "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数据的两种格式。即{"张三" : "男"}  , [{ 张三" : " 男" }] ,使用时需要将其转换成对应的对象。

如(示例):

?

1

2

JSONObject jsonObject = JSONObject.fromObject(json);   //将json字符串转换为JSONObject

JSONArray jsonArray = JSONArray.fromObject(json);  //将json字符串转换为JSONArray

还有一点需要指出:在取键值是始终需要根据键取值,从外到内,取内层的键的值需要先获取外层键的值,如果跨越取值会报错。

下面演示取值:

?

1

2

3

4

5

6

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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中的属性,方法如下:

?

1

2

3

4

5

//将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); //能获取到数据

最后附上部分代码:

?

CopyRight:2016-2025好得很程序员自学网 备案ICP:湘ICP备09009000号-16 http://www.haodehen.cn
本站资讯不构成任何建议,仅限于个人分享,参考须谨慎!
本网站对有关资料所引致的错误、不确或遗漏,概不负任何法律责任。
本网站刊载的所有内容(包括但不仅限文字、图片、LOGO、音频、视频、软件、程序等)版权归原作者所有。任何单位或个人认为本网站中的内容可能涉嫌侵犯其知识产权或存在不实内容时,请及时通知本站,予以删除。

网站内容来源于网络分享,如有侵权发邮箱到:kenbest@126.com,收到邮件我们会即时下线处理。
网站框架支持:HDHCMS   51LA统计 百度统计
Copyright © 2018-2025 「好得很程序员自学网
[ SiteMap ]

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

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 id="codetool">

到此这篇关于Java JSONObject与JSONArray对象案例详解的文章就介绍到这了,更多相关Java JSONObject与JSONArray对象内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://HdhCmsTestcnblogs测试数据/jhcai/p/7910350.html

查看更多关于Java JSONObject与JSONArray对象案例详解的详细内容...

  阅读:13次