Gson使用中的一個小竅門
正式做Android和蘋果開發有一年的時間了,一直想寫篇文章,但是一直比較忙沒時間下筆(其實就給自己找理由,其實就是懶),今天在使用gson解析使用遇到了設置的字段網絡返回的數據是null的問題,有的用戶這個字段是有返回值,這個字段必須要有,那麼這個問題該怎麼解決呢?網絡也許有更好解決辦法,我沒有查,我只是提供了我自己的解決辦法,各位看客也可以看看別人是怎麼解決的,如果有好的建議,一起學習一下。好了不賣關子了,下面看看具體的解決辦法吧。
不多說了,直接上代碼了代碼
從代碼中可以看到,代碼中有3個字段,其中tbusername和alipay是可能返回null的字段
public class UserInformationCell {
private int id;
private String tbusername;
private String alipay;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTBUsername() {
return tbusername;
}
//對於返回值可能爲空的字段,只需要檢查並賦值就好了
public void setTBUsername(String tbusername) {
this.tbusername = (tbusername != null) ? tbusername : "";
}
public String getAlipay() {
return alipay;
}
//對於返回值可能爲空的字段,只需要檢查並賦值就好了
public void setAlipay(String alipay) {
this.alipay = (alipay != null) ? alipay : "";
}
}