JSONObject和JSONArray区别及基本用法(转)

 

1、JSONObject和JSONArray的数据表示形式json

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

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

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

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

        表示了包含2个JSONObject的JSONArray。字符串

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

2、如何从字符串String得到JSONObject对象和JSONArray对象it

          JSONObject  jsonObject  = new JSONObject ( String  str);class

         JSONArray jsonArray = new JSONArray(String    str  ) ;test

 

3、如何从JSONArray中得到JSONObject对象

       你们能够把JSONArray当成通常的数组来对待,只是获取的数据内数据的方法不同

                   JSONObject   jsonObject = (JSONObject)jsonArray.get(i);

                   JSONObject   jsonObject  =  jsonArray.getJSONObject(i) ;  

  二者均可。第一种注意转换 

 

4、获取JSON内的数据

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

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

     Strirng jcourse = jsonObject.get("courseID").toString();

 5、通常地 为键值对

                        eg:{  name:"xm", value:"张三"}

                         String jname = null;

                         if(jsonObject.get("name").equals("xm")){

                          jname=jsonObject.get("value").toString();

                        }

相关文章
相关标签/搜索