記錄工作中碰到的一個內容。
原料是微信平台的一個接口json數據。
{ "errcode" : 0, "errmsg" : "ok", "business_list" : [{ "base_info" : { "sid" : "", "business_name" : "xxxxxxxx服務中心", "branch_name" : "", "address" : "xx路8桃源山庄酒樓2層", "telephone" : "0771-56xxxx9", "categories" : ["公司企業,公司企業"], "city" : "xx市", "province" : "xxxx", "offset_type" : 1, "longitude" : 108.391288757, "latitude" : 22.8106937408, "photo_list" : [], "introduction" : "創新民營金融模式,服務區域經濟發展", "recommend" : "", "special" : "", "open_time" : "08:30-17:30", "avg_price" : 0, "poi_id" : "465268573", "available_state" : 3, "district" : "青秀區", "update_status" : 0 } } ], "total_count" : 1 }
封裝的方法需要將這個數據轉換為一個java對象作為返回值。
分析數據結構,先從最簡單的開始。首先最里層的數據需要一個base_info輔助對象。
比如說是類StoreBaseInfo:
package com.gxgrh.wechat.wechatapi.responseentity.store; import com.google.gson.annotations.SerializedName; import java.util.List; /**門店信息基礎類 * Created by Administrator on 2016/12/7. */ public class StoreBaseInfo { private String sid; @SerializedName("business_name") private String businessName; @SerializedName("branch_name") private String branchName; private String address; private String telephone; private List<String> categories; private String city; private String province; @SerializedName("offset_type") private String offsetType; private float longitude; private float latitude; @SerializedName("photo_list") private List<PhotoUrl> photoList; private String recommend; private String special; private String introduction; @SerializedName("open_time") private String openTime; @SerializedName("avg_price") private float avgPrice; @SerializedName("available_state") private int availableState; @SerializedName("update_status") private int updateStatus; @SerializedName("poiId") private String poiId; private String district; }
其次,business_list節點的數據是一個對象數組,所以需要針對數組中的對象再設計一個輔助類。
比如說是類StoreBaseInfoRsp:
import com.google.gson.annotations.SerializedName; /** * Created by Administrator on 2016/12/7. */ public class StoreBaseInfoRsp { @SerializedName("base_info") private StoreBaseInfo storeBaseInfo; public StoreBaseInfo getStoreBaseInfo() { return storeBaseInfo; } public void setStoreBaseInfo(StoreBaseInfo storeBaseInfo) { this.storeBaseInfo = storeBaseInfo; } }
然后就可以得到最終的類。
比如說是類StoreListRsp:
import com.google.gson.annotations.SerializedName; import java.util.List; /** 查詢門店列表返回的數據 * Created by Administrator on 2016/12/7. */ public class StoreListRsp { private String errcode; private String errmsg; @SerializedName("total_count") private int totalCount; public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } @SerializedName("business_list") private List<StoreBaseInfoRsp> businessList; }
利用方法:
StoreListRsp storeListRsp = new Gson().fromJson(jsonResponse ,StoreListRsp.class);
就可以獲得類對象了。記得引入Gson包。