- Android:使用Gson結合泛型類靈活解析JSON數據
- 發布時間:2016/1/15 來源:搜數網絡 瀏覽:59
一般比較規范的后端JSON返回數據,會遵循一些指定的JSON格式,比如:
錯誤:
- {
- "status": -1,
- "data": null,
- "err": "not_found"
- }
- {
- "status": 0,
- "data": {
- "price": 4,
- "name": "脈動",
- "type": "飲料",
- "amount": 50,
- "summary": "隨時隨地,脈動回來",
- "picture": "http://www.jpjy365.com/images/201402/source_img/29726_G_1393285888119.jpg",
- "hot": true,
- "sales": 100
- },
- "err": null
- }
- public class UniApiResult {
- @SerializedName("status")
- private int mStatus;
- @SerializedName("err")
- private String mErr;
- @SerializedName("data")
- private T mData;
- public int getStatus() {
- return mStatus;
- }
- public void setStatus(int status) {
- mStatus = status;
- }
- public String getErr() {
- return mErr;
- }
- public void setErr(String err) {
- mErr = err;
- }
- public T getData() {
- return mData;
- }
- public void setData(T data) {
- mData = data;
- }
- }
- public class GoodsInfoModel {
- @SerializedName("price")
- private int mPrice;
- @SerializedName("name")
- private String mName;
- @SerializedName("type")
- private String mType;
- @SerializedName("amount")
- private int mAmount;
- @SerializedName("summary")
- private String mSummary;
- @SerializedName("picture")
- private String mPicture;
- @SerializedName("hot")
- private boolean mHot;
- @SerializedName("sales")
- private int mSales;
- public int getPrice() {
- return mPrice;
- }
- public void setPrice(int price) {
- mPrice = price;
- }
- public String getName() {
- return mName;
- }
- public void setName(String name) {
- mName = name;
- }
- public String getType() {
- return mType;
- }
- public void setType(String type) {
- mType = type;
- }
- public int getAmount() {
- return mAmount;
- }
- public void setAmount(int amount) {
- mAmount = amount;
- }
- public String getSummary() {
- return mSummary;
- }
- public void setSummary(String summary) {
- mSummary = summary;
- }
- public String getPicture() {
- return mPicture;
- }
- public void setPicture(String picture) {
- mPicture = picture;
- }
- public boolean getHot() {
- return mHot;
- }
- public void setHot(boolean hot) {
- mHot = hot;
- }
- public int getSales() {
- return mSales;
- }
- public void setSales(int sales) {
- mSales = sales;
- }
- }
- /**
- * 數據解析
- *
- * @param jsonStr JSON字符串
- * @return UniApiResult 數據對象
- */
- public UniApiResult parseJson(String jsonStr) {
- Gson gson = new Gson();
-
Type jsonType = new TypeToken
- }.getType();
- return gson.fromJson(jsonStr, jsonType);
- }
原文:http://blog.csdn.net/yuanguozhengjust/article/details/50477128