JSON(一):JSONObject和JSONArray区别及基本用法
一、JSONObject和JSONArray的数据表示形式
- JSONObject的数据是用 { } 来表示的
JSONObject jsonObject =
{ "id" : "123", "courseID" : "huangt-test", "title" : "提交作业", "content" : null }
- JSONArray是由JSONObject构成的数组,用 [ { } , { } , … , { } ] 来表示
JSONArray jsonArray3 = [
{ "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 = (JSONObject)jsonArray.get(i);
JSONObject jsonObject = jsonArray.getJSONObject(i) ;
两者都可。第一种注意转换
四、获取JSON内的数据
int jid= jsonObject.getInt ( "id" ) ; // 这里的jid得到的数据就是123.
String jcourse=jsonObject.getString( " courseID") ; // 这里的jcourse得到的数据就是huangt-test.
Strirng jcourse = jsonObject.get("courseID").toString();