Android用Gson解析JSON字符串

时间:2023-03-09 10:00:22
Android用Gson解析JSON字符串

在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;
}
}