Android-json解析(三):原生JSONObject+JSONArray的解析、遍歷及生成等
阿新 • • 發佈:2018-12-30
一、JSONObject和JSONArray的資料表示形式
JSONObject的資料是用 { } 來表示的,
例如:
{
"id":"1",
"courseID":"化學",
"title":"滴定實驗",
"content":"下週二實驗樓201必須完成"
}
而JSONArray,顧名思義是由JSONObject構成的陣列,用 [ { } , { } , …… , { } ] 來表示
例如:
[
{
"id":"1",
"courseID":"數學",
"title":"一加一等於幾"
},
{
"id":"2",
"courseID":"語文",
"title":"請背誦全文"
}
]
表示了包含2個JSONObject的JSONArray。
可以看到一個很明顯的區別,一個最外面用的是 { } ,一個最外面用的是 [ ] ;
二、如何從字串jsonString獲得JSONObject物件和JSONArray物件
/*json字串最外層是大括號時:*/
JSONObject jsonObject = new JSONObject(jsonStr);
/*json字串最外層是方括號時:*/
JSONArray jsonArray = new JSONArray(jsonStr);
三、如何從JSONArray中獲得JSONObject物件
遇到方括號時,就要先獲取JSONArray,然後再迴圈遍歷出JSONObject
大家可以把JSONArray當成一般的陣列來對待,只是獲取的資料內資料的方法不一樣。
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
注意:
/*JSONObject 獲取jsonArray :需要陣列的欄位名*/
JSONArray jsonArray = jsonObject.getJSONArray("children");
/*jsonArray獲取JSONObject : 需要遍歷陣列*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
四、通過JsonObject獲取JSON內的具體資料:
int mid= jsonObject.getInt("id");
String mcourse=jsonObject.getString("courseID");
示例一:
{
"msg": "",
"code": "succeed",
"login_status": 0,
"mall_uid": "epet_0",
"mall_user": "",
"sys_time": 1494388655,
"push_alias": "",
"push_tags": "version3",
"categorys": [
{
"cateid": 53,
"name": "狗狗玩具",
"children": [
{
"type": "cateid",
"id": "210",
"name": "棉製玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/fcab37ead00d77bcdddf7dabe6c817d7.jpg"
},
{
"type": "cateid",
"id": "211",
"name": "橡膠玩具",
"photo": "http://i.epetbar.com/nowater/2016-07/21/14/874299e54a8cf1488d6b1bead8f8e9bb.jpg"
},
{
"type": "cateid",
"id": "212",
"name": "塑料玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/df1ed7120376370a4b5badaae61a0a7e.jpg"
},
{
"type": "cateid",
"id": "213",
"name": "手工玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/6709410560b999ab37ffb9747bb2ee71.jpg"
},
{
"type": "cateid",
"id": "3088",
"name": "食用玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/a5c7619872749790f6d6fd1ff3eccedc.jpg"
},
{
"type": "cateid",
"id": "4157",
"name": "木質玩具",
"photo": "http://i.epetbar.com/nowater/cates/2014-03/24/e9145de044fd5cec4c9b8ed47360d98f.jpg"
},
{
"type": "cateid",
"id": "4188",
"name": "梵米派",
"photo": "http://i.epetbar.com/nowater/cates/2015-07/28/45c339f6acb56364132b92f04b090c5c.jpg"
}
]
}
],
"topadv": {
"advid": "20605",
"src": "https://img2.epetbar.com/nowater/2017-04/05/14/19427a29344bcc0f385ca4718adca02f.jpg",
"title": "紅腳丫",
"param": {
"mode": "web",
"param": "http://sale.epet.com/m/mould/activity/ztMTAzOA%3D%3D.html?tid=1038"
}
},
"owner": 53
}
解析如下:
注意:MyData類可以藉助GsonFormat類生成實體類。
private List<MyData.CategorysBean.ChildrenBean> parseJSONOrgin(String string) {
List<MyData.CategorysBean.ChildrenBean> childrenBeanList = new ArrayList<MyData.CategorysBean.ChildrenBean>();
try {
JSONObject jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("categorys");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONArray children = jsonObject1.getJSONArray("children");
for (int j = 0; j < children.length(); j++) {
JSONObject jsonObject2 = children.getJSONObject(j);
MyData.CategorysBean.ChildrenBean childrenBean = new MyData.CategorysBean.ChildrenBean();
childrenBean.setName(jsonObject2.getString("name"));
childrenBean.setId(jsonObject2.getString("id"));
childrenBean.setPhoto(jsonObject2.getString("photo"));
childrenBean.setType(jsonObject2.getString("type"));
childrenBeanList.add(childrenBean);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return childrenBeanList;
}
示例二:
[
{
"id": 582490,
"name": "單車自駕:魔幻張家界",
"photos_count": 128,
"start_date": "2016-04-05",
"end_date": "2016-04-08",
"days": 4,
"level": 4,
"views_count": 55199,
"comments_count": 34,
"likes_count": 441,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/582490/1468260328216p1andi510ihgkc2f5hk6rf198.jpg",
"featured": false,
"user": {
"id": 313643,
"name": "huchichi",
"image": "http://tva2.sinaimg.cn/crop.0.12.282.282.50/5c5ee839gw1ec7kq4pasrj207v08d3zv.jpg"
}
},
{
"id": 666746,
"name": "【斯里蘭卡10天】跨過山和大海",
"photos_count": 122,
"start_date": "2016-12-24",
"end_date": "2017-01-02",
"days": 10,
"level": 3,
"views_count": 33023,
"comments_count": 32,
"likes_count": 471,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/666746/1485787660939p1b7ntf07u16kdssn1tfl1ck1q1qd.jpg",
"featured": false,
"user": {
"id": 469471,
"name": "宇_RainyK",
"image": "http://a.chanyouji.cn/469471/1460020629.jpg"
}
},
{
"id": 665223,
"name": "上帝自留地探訪 : 紐西蘭——快樂咔嚓聲",
"photos_count": 250,
"start_date": "2016-11-30",
"end_date": "2016-12-04",
"days": 5,
"level": 3,
"views_count": 23981,
"comments_count": 30,
"likes_count": 533,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1483013211/40p8jhlx7t4e8hntyhp4z31c0.jpg",
"serial_id": 664971,
"serial_position": 1,
"featured": false,
"user": {
"id": 131541,
"name": "片兒川",
"image": "http://a.chanyouji.cn/131541/1483887153821.jpg"
}
},
{
"id": 591454,
"name": "土耳其...我喜歡你,像風走了八千里",
"photos_count": 195,
"start_date": "2016-08-08",
"end_date": "2016-08-22",
"days": 15,
"level": 3,
"views_count": 18822,
"comments_count": 42,
"likes_count": 854,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/1472368913/9896F012-522E-46C4-9F29-5F6D86C790DB.jpg",
"featured": false,
"user": {
"id": 208609,
"name": "晶晶姑姑娘娘",
"image": "http://a.chanyouji.cn/208609/1493099858.jpg"
}
},
{
"id": 589708,
"name": "浪跡非洲最南——“慢得啦”國閒遊之一",
"photos_count": 128,
"start_date": "2016-07-23",
"end_date": "2016-07-24",
"days": 2,
"level": 3,
"views_count": 5858,
"comments_count": 4,
"likes_count": 65,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/589708/1471963416200p1aqrtl1pq8js1ek0sn913uq1kdmh.jpg",
"serial_id": 589708,
"serial_position": 0,
"featured": false,
"user": {
"id": 103122,
"name": "牽著蝸牛散步的JOY",
"image": "http://tva1.sinaimg.cn/crop.0.17.640.640.50/794bd26ajw8e7tg9nfqb5j20hs0iqmxg.jpg"
}
},
{
"id": 598966,
"name": "霓虹國/留學生 夢遊記錄",
"photos_count": 88,
"start_date": "2016-08-28",
"end_date": "2017-05-07",
"days": 253,
"level": 3,
"views_count": 16648,
"comments_count": 10,
"likes_count": 72,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1476365877/C9B59738-58E8-47C9-BCD1-5F2AC5CC9526.jpg",
"featured": false,
"user": {
"id": 694154,
"name": "Y-dec",
"image": "http://q.qlogo.cn/qqapp/100277927/5475C47B95A36891E2698462184F8785/100"
}
},
{
"id": 544528,
"name": "【我的年假】7 重慶—吃一頓地道火鍋",
"photos_count": 385,
"start_date": "2016-08-31",
"end_date": "2016-09-03",
"days": 4,
"level": 3,
"views_count": 37214,
"comments_count": 55,
"likes_count": 530,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/544528/1474011393910p1asoupfpujrj1rnd5o813qo1jvi5.jpg",
"serial_id": 544528,
"serial_position": 0,
"featured": false,
"user": {
"id": 17010,
"name": "馬蘭頭頭2010",
"image": "http://a.chanyouji.cn/17010/1426768814.jpg"
}
},
{
"id": 665311,
"name": "就該這麼玩【北海道】",
"photos_count": 118,
"start_date": "2016-12-05",
"end_date": "2016-12-12",
"days": 8,
"level": 3,
"views_count": 24644,
"comments_count": 6,
"likes_count": 108,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1484295471/E2B2C32A-C910-490F-9F13-BC9D3B118C1B.jpg",
"featured": false,
"user": {
"id": 544219,
"name": "炘仔~",
"image": "http://a.chanyouji.cn/544219/1489641072.jpg"
}
},
{
"id": 668998,
"name": "漫步成都一一我的尋(熊)貓之旅",
"photos_count": 108,
"start_date": "2017-02-06",
"end_date": "2017-02-12",
"days": 7,
"level": 3,
"views_count": 15222,
"comments_count": 30,
"likes_count": 146,
"source": "app",
"front_cover_photo_url": "http://p.chanyouji.cn/1487129075/720F81CB-EE64-4681-8564-A9A6864AAD33.jpg",
"featured": false,
"user": {
"id": 261578,
"name": "小檸12345",
"image": "http://tva1.sinaimg.cn/crop.27.0.238.238.50/bb9ff9e8gw1eggbljiopfj208w06oaam.jpg"
}
},
{
"id": 297060,
"name": "「吃遍日本」大阪·神戶·名古屋",
"photos_count": 125,
"start_date": "2015-04-25",
"end_date": "2015-05-02",
"days": 8,
"level": 4,
"views_count": 56384,
"comments_count": 121,
"likes_count": 948,
"source": "web",
"front_cover_photo_url": "http://p.chanyouji.cn/297060/1440912374444p19tuh3ukup7t1l5c1j0u8r6kfs2.jpg",
"featured": false,
"user": {
"id": 312316,
"name": "CaitlinGao",
"image": "http://tva3.sinaimg.cn/crop.0.0.640.640.50/96246e0bjw8ensjycmsdmj20hs0hsjs7.jpg"
}
}
]
解析如下:
注意:最外層是個方括號。
private List<News> parseJSONOrgin(String json) {
List<News> list = new ArrayList<News>();
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
News news = new News();
news.setSource(jsonObject.getString("source"));
news.setFront_cover_photo_url(jsonObject.getString("front_cover_photo_url"));
news.setName(jsonObject.getString("name"));
news.setStart_date(jsonObject.getString("start_date"));
list.add(news);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
JSONObject獲取Float Double型別資料的準確性:
示例:
{
"status":0,
"result":[
{
"x":114.2307489832,
"y":29.579081808346
}
]
}
解析如下:
String jsonStr = "{\"status\":0,\"result\":[{\"x\":114.2307489832,\"y\":29.579081808346}]}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject.has("result")) {
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectResult = jsonArray.getJSONObject(i);
if (jsonObjectResult.has("x")) {
//方法一:
String x = jsonObjectResult.getString("x");
System.out.println("x============" + x);//114.2307489832
Double aDouble = Double.valueOf(x);
System.out.println("aDouble=======" + aDouble);//114.2307489832
//方法二:
String x1 = jsonObjectResult.get("x").toString();
System.out.println("x1============" + x1);//114.2307489832
Double aDouble1 = Double.valueOf(x1);
System.out.println("aDouble1=======" + aDouble1);//114.2307489832
//方法三
double x2 = jsonObjectResult.getDouble("x");
System.out.println("x2============" + x2);//114.2307489832
//獲取失敗
long x3 = jsonObjectResult.getLong("x");
System.out.println("x3============" + x3);//114
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
判斷字串是JSONObject還是JSONArray
使用 JSONTokener。JSONTokener.nextValue() 會給出一個物件,然後可以動態的轉換為適當的型別。
示例一:
有時候這樣:
{
"id":"1",
"courseID":"化學",
"title":"滴定實驗",
"content":"下週二實驗樓201必須完成"
}
有時候又這樣:
[
{
"id":"1",
"courseID":"數學",
"title":"一加一等於幾"
},
{
"id":"2",
"courseID":"語文",
"title":"請背誦全文"
}
]
解析如下:
//String jsonStr = "{\"id\":\"1\",\"courseID\":\"化學\",\"title\":\"滴定實驗\",\"content\":\"下週二實驗樓201必須完成\"}";
String jsonStr = "[{\"id\":\"1\",\"courseID\":\"數學\",\"title\":\"一加一等於幾\"},{\"id\":\"2\",\"courseID\":\"語文\",\"title\":\"請背誦全文\"}]";
try {
Object object = new JSONTokener(jsonStr).nextValue();
if (object instanceof JSONObject) {
System.out.println("==我是JSONObject==");
JSONObject jsonObject = (JSONObject) object;
if (jsonObject.has("title")) {
String title = jsonObject.getString("title");
if (!TextUtils.isEmpty(title)) {
System.out.println("title==" + title);
}
}
} else if (object instanceof JSONArray) {
System.out.println("==我是JSONArray==");
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if (jsonObject.has("title")) {
String title = jsonObject.getString("title");
if (!TextUtils.isEmpty(title)) {
System.out.println("title==" + title);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
示例二:
有時候這樣:
{
"cource":{
"id":"1",
"courseID":"數學",
"title":"一加一等於幾"
}
}
有時候又這樣:
{
"cource":[
{
"id":"1",
"courseID":"數學",
"title":"一加一等於幾"
},
{
"id":"2",
"courseID":"語文",
"title":"請背誦全文"
}
]
}
解析如下:
String jsonStr="{\"cource\":[{\"id\":\"1\",\"courseID\":\"數學\",\"title\":\"一加一等於幾\"},{\"id\":\"2\",\"courseID\":\"語文\",\"title\":\"請背誦全文\"}]}";
//String jsonStr = "{\"cource\":{\"id\":\"1\",\"courseID\":\"數學\",\"title\":\"一加一等於幾\"}}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
if (jsonObject.has("cource")) {
String cource = jsonObject.getString("cource");
Object object = new JSONTokener(cource).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
for (int k = 0; k < jsonArray.length(); k++) {
JSONObject parameterObject = jsonArray.getJSONObject(k);
System.out.println("==我是JSONArray==" + parameterObject);
}
} else if (object instanceof JSONObject) {
JSONObject jsonObject1 = (JSONObject) object;
System.out.println("==我是JSONObject==" + jsonObject1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
opt與get的區別:
get()取值不正確會丟擲異常,必須用try catch或者throw包起
而opt()取值不正確則會試圖進行轉化或者輸出友好值,不會丟擲異常
json中的opt和get方法
get()和opt()
getBoolean()和optBoolean();
getDouble()和optDouble();
getInt()和optInt();
getLong()和optLong();
getString()和optString();
getJSONObject和optJSONobject();
getJSONArray和optJSONArray();
getJSONArray和optJSONArray()原始碼對比:
/**
* Returns the value mapped by {@code name} if it exists and is a {@code
* JSONArray}, or throws otherwise.
*
* @throws JSONException if the mapping doesn't exist or is not a {@code
* JSONArray}. 不存在或不是jsonArray丟擲異常
*/
public JSONArray getJSONArray(String name) throws JSONException {
Object object = get(name);
if (object instanceof JSONArray) {
return (JSONArray) object;
} else {
throw JSON.typeMismatch(name, object, "JSONArray");
}
}
/**
* Returns the value mapped by {@code name} if it exists and is a {@code
* JSONArray}, or null otherwise. 不存在或不是jsonArray返回null
*/
public JSONArray optJSONArray(String name) {
Object object = opt(name);
return object instanceof JSONArray ? (JSONArray) object : null;
}
getString 可以看出 返回的任何資料型別都會被轉換為String
public String getString(String name) throws JSONException {
Object object = get(name);
String result = JSON.toString(object);
if (result == null) {
throw JSON.typeMismatch(name, object, "String");
}
return result;
}
json的建立:
通過put方法來設定json的建立。
try {
createJson();
} catch (JSONException e) {
e.printStackTrace();
}
private String createJson() throws JSONException {
JSONObject jsonObject = new JSONObject();
jsonObject.put("intKey", 123);
jsonObject.put("doubleKey", 10.1);
jsonObject.put("longKey", 666666666);
jsonObject.put("stringKey", "lalala");
jsonObject.put("booleanKey", true);
JSONArray jsonArray = new JSONArray();
jsonArray.put(0, 111);
jsonArray.put("second");
jsonObject.put("arrayKey", jsonArray);
JSONObject innerJsonObject = new JSONObject();
innerJsonObject.put("innerStr", "inner");
jsonObject.put("innerObjectKey", innerJsonObject);
System.out.println("建立的json=======" + jsonObject.toString());
return jsonObject.toString();
}
列印結果:
{
"intKey":123,
"doubleKey":10.1,
"longKey":666666666,
"stringKey":"lalala",
"booleanKey":true,
"arrayKey":[
111,
"second"
],
"innerObjectKey":{
"innerStr":"inner"
}
}
遍歷key和value:
示例一:jsonobject
{
"id":"1",
"courseID":"化學",
"title":"滴定實驗",
"content":"下週二實驗樓201必須完成"
}
String jsonStr = "{\"id\":\"1\",\"courseID\":\"化學\",\"title\":\"滴定實驗\",\"content\":\"下週二實驗樓201必須完成\"}";
try {
JSONObject jsonObject = new JSONObject(jsonStr);
Iterator iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();
String value = jsonObject.getString(key);
System.out.println(key + "===" + value);
}
} catch (JSONException e) {
e.printStackTrace();
}
示例二:jsonarray
[
{
"id":"1",
"courseID":"數學",
"title":"一加一等於幾"
},
{
"id":"2",
"courseID":"語文",
"title":"請背誦全文"
}
]
String jsonStr = "[{\"id\":\"1\",\"courseID\":\"數學\",\"title\":\"一加一等於幾\"},{\"id\":\"2\",\"courseID\":\"語文\",\"title\":\"請背誦全文\"}]";
try {
JSONArray jsonArray = new JSONArray(jsonStr);
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++)