JSONObject和JSONArray区别及基本用法

来源:互联网 发布:dw制作淘宝导航条 编辑:程序博客网 时间:2024/05/16 08:06

一、JSONObject和JSONArray的数据表示形式

JSONObject的数据是用 {  } 来表示的,

        例如:   { "id" : "123", "courseID" : "huangt-test", "title" : "提交作业", "content" : null  }  

而JSONArray,顾名思义是由JSONObject构成的数组,用  [ { } , { } , ......  , { } ]  来表示

       例如:   [ {  "id" : "123", "courseID" : "huangt-test", "title" : "提交作业" }  ,  {  "content" : null, "beginTime" : 1398873600000  "endTime" } ]; 

        表示了包含2个JSONObject的JSONArray。

可以看到一个很明显的区别,一个最外面用的是 {  }  ,一个最外面用的是 [  ]  ;


二、如何从字符串String获得JSONObject对象和JSONArray对象

          JSONObject  jsonObject  = new JSONObject ( String  str);

         JSONArray jsonArray = new JSONArray(String    str  ) ;


三、如何从JSONArray中获得JSONObject对象

       大家可以把JSONArray当成一般的数组来对待,只是获取的数据内数据的方法不一样

                   JSONObject   jsonObject  =  jsonArray.getJSONObject(i) ;    


四、获取JSON内的数据

      int   mid= jsonObject.getInt ( "id" );    //  这里的mid得到的数据就是123.

      String  mcourse=jsonObject.getString( " courseID");   // 这里的mcourse得到的数据就是huangt-test.

的,

河汉江淮

3 0