Gson解析空字符串發(fā)生異常的處理方法
前言
在實(shí)際開(kāi)發(fā)項(xiàng)目中,服務(wù)器經(jīng)常會(huì)用空字符串 “” 作為返回結(jié)果表示空值 ,但這在Gson當(dāng)中就會(huì)遇到問(wèn)題,如果這項(xiàng)數(shù)據(jù)的類(lèi)型不是字符串,Gson解析就會(huì)報(bào)錯(cuò)
Json異常情況
先來(lái)看一個(gè)后臺(tái)返回的json
正常情況下json:
{
"code":0,
"msg":"ok",
"data":{
"id":5638,
"newsId":5638
}
}
data部分對(duì)應(yīng)的實(shí)體類(lèi):
public class JsonBean {
private int id;
private int newsId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNewsId() {
return newsId;
}
public void setNewsId(int newsId) {
this.newsId = newsId;
}
}
異常情況json(后臺(tái)數(shù)據(jù)庫(kù)newsId字段未查詢(xún)到對(duì)應(yīng)數(shù)據(jù)):
{
"code":0,
"msg":"ok",
"data":{
"id":5638,
"newsId":""
}
}
這樣Gson在解析時(shí)就會(huì)拋出解析錯(cuò)誤的異常,app崩潰,原因是無(wú)法將""轉(zhuǎn)化為int
json異常的處理
我們期望在后臺(tái)返回的json異常時(shí),也能解析成功,空值對(duì)應(yīng)的轉(zhuǎn)換為默認(rèn)值,如:newsId=0;
這里排除掉后臺(tái)開(kāi)發(fā)人員輸出時(shí)給你做矯正,還是得靠自己啊---
我們寫(xiě)一個(gè)針對(duì)int值的類(lèi)型轉(zhuǎn)換器,需要實(shí)現(xiàn)Gson的 JsonSerializer<T> 接口和 JsonDeserializer<T> ,即序列化和反序列化接口
public class IntegerDefault0Adapter implements JsonSerializer<Integer>, JsonDeserializer<Integer> {
@Override
public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定義為int類(lèi)型,如果后臺(tái)返回""或者null,則返回0
return 0;
}
} catch (Exception ignore) {
}
try {
return json.getAsInt();
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src);
}
}
同理Long及Double類(lèi)型
double=>
public class DoubleDefault0Adapter implements JsonSerializer<Double>, JsonDeserializer<Double> {
@Override
public Double deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定義為double類(lèi)型,如果后臺(tái)返回""或者null,則返回0.00
return 0.00;
}
} catch (Exception ignore) {
}
try {
return json.getAsDouble();
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src);
}
}
long=>
public class LongDefault0Adapter implements JsonSerializer<Long>, JsonDeserializer<Long> {
@Override
public Long deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定義為long類(lèi)型,如果后臺(tái)返回""或者null,則返回0
return 0l;
}
} catch (Exception ignore) {
}
try {
return json.getAsLong();
} catch (NumberFormatException e) {
throw new JsonSyntaxException(e);
}
}
@Override
public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src);
}
}
所以使用是這樣的:
return new Retrofit.Builder()
.client(okHttpClient)//設(shè)置網(wǎng)絡(luò)訪問(wèn)框架
.addConverterFactory(GsonConverterFactory.create(buildGson()))//添加json轉(zhuǎn)換框架
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())//讓Retrofit支持RxJava
.baseUrl(baseUrl)
.build();
/**
* 增加后臺(tái)返回""和"null"的處理
* 1.int=>0
* 2.double=>0.00
* 3.long=>0L
*
* @return
*/
public static Gson buildGson() {
if (gson == null) {
gson = new GsonBuilder()
.registerTypeAdapter(Integer.class, new IntegerDefault0Adapter())
.registerTypeAdapter(int.class, new IntegerDefault0Adapter())
.registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
.registerTypeAdapter(double.class, new DoubleDefault0Adapter())
.registerTypeAdapter(Long.class, new LongDefault0Adapter())
.registerTypeAdapter(long.class, new LongDefault0Adapter())
.create();
}
return gson;
}
再也不會(huì)因?yàn)楹笈_(tái)json字段為空的情況崩潰了
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能有所幫助,如果有疑問(wèn)大家可以留言交流。
- gson對(duì)象序列化的示例
- kotlin gson反序列化默認(rèn)值失效深入講解
- java如何利用FastJSON、Gson、Jackson三種Json格式工具自定義時(shí)間序列化
- GSON實(shí)現(xiàn)Java對(duì)象的JSON序列化與反序列化的實(shí)例教程
- Java中Gson的使用詳解
- Java實(shí)現(xiàn)操作JSON的便捷工具類(lèi)完整實(shí)例【重寫(xiě)Google的Gson】
- Java中利用gson解析Json實(shí)例教程
- Android利用Gson解析嵌套多層的Json的簡(jiǎn)單方法
- GSON實(shí)現(xiàn)Java對(duì)象與JSON格式對(duì)象相互轉(zhuǎn)換的完全教程
- 舉例講解Java的JSON類(lèi)庫(kù)GSON的基本用法
- Java的JSON格式轉(zhuǎn)換庫(kù)GSON的初步使用筆記
- Gson如何序列化內(nèi)部類(lèi)
相關(guān)文章
Mybatis之通用Mapper動(dòng)態(tài)表名及其原理分析
這篇文章主要介紹了Mybatis之通用Mapper動(dòng)態(tài)表名及其原理分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
Java算法之時(shí)間復(fù)雜度和空間復(fù)雜度的概念和計(jì)算
這篇文章主要介紹了Java算法之時(shí)間復(fù)雜度和空間復(fù)雜度的概念和計(jì)算,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05
Spring中的@Autowired、@Qualifier和@Primary注解詳解
這篇文章主要介紹了Spring中的@Autowired、@Qualifier和@Primary注解詳解,@Autowired?注解,可以對(duì)類(lèi)成員變量、方法和構(gòu)造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作,@Autowired?是默認(rèn)根據(jù)?byType?進(jìn)行自動(dòng)裝配的,需要的朋友可以參考下2023-11-11
SpringBoot整合MongoDB的實(shí)現(xiàn)代碼
自己本科時(shí)候一直使用的是Mysql,目前的課題組使用的是MongoDB,因此就花了一部分時(shí)間整理了一下,實(shí)現(xiàn)springboot與MongoDB的整合,并且實(shí)現(xiàn)基本的增刪改查操作,從頭到尾給出一個(gè)完整的案例。2021-05-05
淺談Java中ArrayList線(xiàn)程不安全怎么辦
本文主要介紹了Java中ArrayList線(xiàn)程不安全怎么辦,主要有三種解決的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Java多線(xiàn)程CountDownLatch的實(shí)現(xiàn)
本文主要介紹了Java多線(xiàn)程CountDownLatch的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Java的BigDecimal在math包中提供的API類(lèi)場(chǎng)景使用詳解
這篇文章主要介紹了Java的BigDecimal在math包中提供的API類(lèi)場(chǎng)景使用詳解,BigDecimal,用來(lái)對(duì)超過(guò)16位有效位的數(shù)進(jìn)行精確的運(yùn)算,雙精度浮點(diǎn)型變量double可以處理16位有效數(shù),在實(shí)際應(yīng)用中,需要對(duì)更大或者更小的數(shù)進(jìn)行運(yùn)算和處理,需要的朋友可以參考下2023-12-12

