標籤:
在volley架構中有一個 protected Response<Result<T>> parseNetworkResponse(NetworkResponse response){}函數。從伺服器上或者在緩衝中擷取的JSON字串在這個函數進行解析。
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, HTTP.UTF_8)) Result<T> result = GsonUtil.getResult(jsonString, mTypeToken);
我們可以定義一個GsonUtil類。裡面寫一些Gson和JSON相互轉化的功能函數。例如上用到的getResult函數。利用該函數擷取的Result<T>這個JavaBean。也就是返回的規範,該規範由前端開發人員和後台開發人員商量得出。既然得到的JavaBean,那麼我再要擷取JSON裡面的資料就像從一個類中擷取一個資料一樣簡單了。
public static <T> T getResult(String jsonData, TypeToken<T> type) { Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); return (T) gson.fromJson(jsonData, type.getType()); }
Result<T>類:例如:(後台返回的JSON字串形如:{"err":"success","errno":1,"rsm{"userId":"1","email":"?","password":"?","firstName":"胡","lastName":"安","gender":"1","photo":"/picture/userPhoto/1422624411423.PNG","autograph":"","introduce":"","createTime":"4天前"}}失敗返回{"err":"使用者不存在!",errno":0} )
package whu.cn.whushare.bean;import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName;public class Result<T> { @Expose @SerializedName("currentPage") private long currentPage; @Expose @SerializedName("pageSize") private long pageSize; @Expose @SerializedName("allDataCount") private long allDataCount; @Expose @SerializedName("nextPage") private long nextPage; @Expose @SerializedName("errno") private int code; @Expose @SerializedName("err") private String msg; private int total; @Expose @SerializedName("rsm") private T content; public Result(T result) { this.content = result; } public Result(int code, T result) { this.code = code; this.content = result; } public long getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public long getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public long getAllDataCount() { return allDataCount; } public void setAllDataCount(int allDataCount) { this.allDataCount = allDataCount; } public long getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } 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; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public T getContent() { return content; } public void setContent(T content) { this.content = content; }}
Android用Gson解析JSON字串