使用Gson结合泛型类灵活解析JSON数据

时间:2021-07-11 19:26:30

一般比较规范的后端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
}
那么我们可以定义一个通用数据类,比如叫做:UniApiResult

public class UniApiResult<T> {

    @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;
    }
}
然后,我们在需要解析数据特定的数据时,只需要根据特定的数据类型定义一个Model就可以了,如:

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<GoodsInfoModel> 数据对象
*/
public UniApiResult<GoodsInfoModel> parseJson(String jsonStr) {
    Gson gson = new Gson();
    Type jsonType = new TypeToken<UniApiResult<GoodsInfoModel>>() {
    }.getType();
    return gson.fromJson(jsonStr, jsonType);
}
值得注意的是,TypeToken的用法,TypeToken是Gson库中包含的一种获取JSON类型的类,可以传入泛型来获取类型,而getType或getClass这种方法是获取不到泛型类型的,所以Gson解析泛型类型数据的关键就是TypeToken,这个方法解析完成后,即可返回UniApiResult<GoodsInfoModel>类型的对象,通过getData()方法,就可以获取到GoodsInfoModel类型的对象数据了,是不是很省事了呢?


转载请注明出处:http://blog.csdn.net/yuanguozhengjust/article/details/50477128