1. 程式人生 > >Android Gson深入分析

Android Gson深入分析

目前解析json有三種工具:org.json(Java常用的解析),fastjson(阿里巴巴工程師開發的),Gson(Google官網出的),解析速度最快的是Gson,下載地址:https://code.google.com/p/google-gson/

什麼是JSON:

JSON即JavaScript Object Natation, 它是一種輕量級的資料交換格式, 與XML一樣, 是廣泛被採用的客戶端和服務端互動的解決方案.

JSON物件: 

JSON中物件(Object)以"{"開始, 以"}"結束. 物件中的每一個item都是一個key-value對, 表現為"key:value"的形式, key-value對之間使用逗號分隔. 如:{"name":"coolxing", "age"=24, "male":true, "address":{"street":"huiLongGuan", "city":"beijing", "country":"china"}}. JSON物件的key只能是string型別的, 而value可以是string, number, false, true, null, Object物件甚至是array陣列, 也就是說可以存在巢狀的情況.

JSON陣列: 

JSON陣列(array)以"["開始, 以"]"結束, 陣列中的每一個元素可以是string, number, false, true, null, Object物件甚至是array陣列, 陣列間的元素使用逗號分隔. 如["coolxing", 24, {"street":"huiLongGuan", "city":"beijing", "country":"china"}].

Gson的基本使用方法:

通過獲取JsonReader物件解析JSON資料:

String jsonData = "[{\"username\":\"arthinking\",\"userId\":001},{\"username\":\"Jason\",\"userId\":002}]";
try{
	JsonReader reader = new JsonReader(new StringReader(jsonData));
	reader.beginArray();
	while(reader.hasNext()){
		reader.beginObject();
		while(reader.hasNext()){
			String tagName = reader.nextName();
			if(tagName.equals("username")){
				System.out.println(reader.nextString());
			}
			else if(tagName.equals("userId")){
				System.out.println(reader.nextString());
			}
		}
		reader.endObject();
	}
	reader.endArray();
}
catch(Exception e){
	e.printStackTrace();
}

通過把JSON資料對映成一個物件,使用Gson物件的fromJson()方法獲取一個物件陣列進行操作:

建立JSON資料對應的一個POJO物件User.java:

public class User {
	private String username ;
	private int userId ;
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
}

使用Gson物件獲取User物件資料進行相應的操作:

Type listType = new TypeToken<LinkedList<User>>(){}.getType();
Gson gson = new Gson();
LinkedList<User> users = gson.fromJson(jsonData, listType);
for (Iterator iterator = users.iterator(); iterator.hasNext();) {
	User user = (User) iterator.next();
	System.out.println(user.getUsername());
	System.out.println(user.getUserId());
}

如果要處理的JSON字串只包含一個JSON物件,則可以直接使用fromJson獲取一個User物件:

String jsonData = "{\"username\":\"arthinking\",\"userId\":001}";
Gson gson = new Gson();
User user = gson.fromJson(jsonData, User.class);
System.out.println(user.getUsername());
System.out.println(user.getUserId());
解析複雜例項:

資料格式:

{
    "data": {
        "partnerteamlist": [
            {
                "pteamId": 72825,
                "ptitle": "隨攝影/共6套服裝/準爸準媽共拍/免費肚畫/底片全送。",
                "pteamprice": 288
            },
            {
                "pteamId": 72598,
                "ptitle": "隨攝影/拍攝200張/4本相簿/品質拍攝/送全新婚紗。",
                "pteamprice": 2888
            },
            {
                "pteamId": 72613,
                "ptitle": "隨攝影/送全新婚紗/多外景拍攝/服裝不限數量/絕無二次消費!",
                "pteamprice": 3699
            },
            {
                "pteamId": 72638,
                "ptitle": "隨攝影/服裝不限數量/高品質拍攝260張/送全新婚紗。",
                "pteamprice": 4299
            },
            {
                "pteamId": 72716,
                "ptitle": "隨攝影/3組服裝造型/內外景拍攝/完全透明消費!",
                "pteamprice": 388
            }
        ],
        "liketeamlist": [
            {
                "lteamId": 65886,
                "ltitle": "愛麗爾婚紗攝影/2本相簿/6套服裝造型/拍攝不限最低拍攝150張。",
                "limage": "http://img.pztuan.com/upfile/team/2013/0712/201307120257551465.jpg",
                "lteamprice": 518,
                "lmarketprice": 3999
            },
            {
                "lteamId": 57133,
                "ltitle": "陶冶攝影/婚紗閨蜜/6組服裝造型/拍攝不低於120張!",
                "limage": "http://img.pztuan.com/upfile/team/2013/0628/201306281115249737.jpg",
                "lteamprice": 580,
                "lmarketprice": 3380
            }
        ],
        "feedbacks": {
            "feedbacklist": [
                {
                    "comment": "5分",
                    "createtime": "2014.07.08 13:38",
                    "score": 5,
                    "username": "l***2"
                }
            ],
            "totalcount": 1,
            "totalscore": 5
        }
    },
    "err": null,
    "state": 1
}

實體類(裡面的成員變數和介面的返回值名稱一 一對應才能保證解析正確):
package com.pztuan.entity;

import java.util.List;

public class OtherDetail {

	private int state;
	private List<err> err;
	private OtherDetail2 data;

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public List<err> getErr() {
		return err;
	}

	public void setErr(List<err> err) {
		this.err = err;
	}

	public OtherDetail2 getData() {
		return data;
	}

	public void setData(OtherDetail2 data) {
		this.data = data;
	}

	public class OtherDetail2 {
		private List<partnerteamlist> partnerteamlist;
		private List<liketeamlist> liketeamlist;
		private List<feedbacks> feedbacks;

		public List<liketeamlist> getLiketeamlist() {
			return liketeamlist;
		}

		public void setLiketeamlist(List<liketeamlist> liketeamlist) {
			this.liketeamlist = liketeamlist;
		}

		public List<feedbacks> getFeedbacks() {
			return feedbacks;
		}

		public void setFeedbacks(List<feedbacks> feedbacks) {
			this.feedbacks = feedbacks;
		}

		public class partnerteamlist {
			private int pteamId;
			private String ptitle;
			private Double pteamprice;

			public int getPteamId() {
				return pteamId;
			}

			public void setPteamId(int pteamId) {
				this.pteamId = pteamId;
			}

			public String getPtitle() {
				return ptitle;
			}

			public void setPtitle(String ptitle) {
				this.ptitle = ptitle;
			}

			public Double getPteamprice() {
				return pteamprice;
			}

			public void setPteamprice(Double pteamprice) {
				this.pteamprice = pteamprice;
			}

		}

		public class liketeamlist {
			private int lteamId;
			private String ltitle;
			private String limage;
			private Double lteamprice;
			private Double lmarketprice;

			public int getLteamId() {
				return lteamId;
			}

			public void setLteamId(int lteamId) {
				this.lteamId = lteamId;
			}

			public String getLtitle() {
				return ltitle;
			}

			public void setLtitle(String ltitle) {
				this.ltitle = ltitle;
			}

			public String getLimage() {
				return limage;
			}

			public void setLimage(String limage) {
				this.limage = limage;
			}

			public Double getLteamprice() {
				return lteamprice;
			}

			public void setLteamprice(Double lteamprice) {
				this.lteamprice = lteamprice;
			}

			public Double getLmarketprice() {
				return lmarketprice;
			}

			public void setLmarketprice(Double lmarketprice) {
				this.lmarketprice = lmarketprice;
			}
		}

		public class feedbacks {
			private int totalcount;
			private Double totalscore;
			private List<feedbacklist> feedbacklist;

			public int getTotalcount() {
				return totalcount;
			}

			public void setTotalcount(int totalcount) {
				this.totalcount = totalcount;
			}

			public Double getTotalscore() {
				return totalscore;
			}

			public void setTotalscore(Double totalscore) {
				this.totalscore = totalscore;
			}

			public List<feedbacklist> getFeedbacklist() {
				return feedbacklist;
			}

			public void setFeedbacklist(List<feedbacklist> feedbacklist) {
				this.feedbacklist = feedbacklist;
			}

			public class feedbacklist {
				private String username;
				private String comment;
				private String createtime;
				private Double score;

				public String getUsername() {
					return username;
				}

				public void setUsername(String username) {
					this.username = username;
				}

				public String getComment() {
					return comment;
				}

				public void setComment(String comment) {
					this.comment = comment;
				}

				public String getCreatetime() {
					return createtime;
				}

				public void setCreatetime(String createtime) {
					this.createtime = createtime;
				}

				public Double getScore() {
					return score;
				}

				public void setScore(Double score) {
					this.score = score;
				}

			}
		}

		public List<partnerteamlist> getPartnerteamlist() {
			return partnerteamlist;
		}

		public void setPartnerteamlist(List<partnerteamlist> partnerteamlist) {
			this.partnerteamlist = partnerteamlist;
		}
	}

	public class err {
		private int code;
		private String msg;

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}
	}
}

注意上面內部類的運用。

解析:

Gson gson = new Gson();
OtherDetail d = gson.fromJson(jsonString,Detail.class);//取值的時候就從父類一層一層調子類成員(重要)

若出現引用異常,請檢視Java內部類設計原則。

如有問題請留言,轉載註明出處。