- 现在一般都是用Retrofit 封装okhttp的请求框架
需要添加GsonConverterFactory.create(gson),
而有时候gson中一些字段可能为null
数组可能为空 而可能产生bug引起程序崩溃
Gson gson = new GsonBuilder()
.registerTypeAdapter(
List.class,new MyListAdapter())//可添加N个typeAdapter根据业务需要
.registerTypeAdapter(
String.class,new MyStringAdapter()).create();
retrofit = new Retrofit.Builder()
.baseUrl(baseUri) //Set the Api Base URL
.client(okHttpClient) //The HTTP client used for requests.
.addConverterFactory(
GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
2.数组适配器
package xxx.typeadapter;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class MyListAdapter<T> implements JsonSerializer<List<?>>, JsonDeserializer {
@Override
public JsonElement serialize(List<?> src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(new Gson().toJson(src));
}
@Override
public Object deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
try {
if (json.getAsJsonArray() == null) {//定义为JsonArray类型
return new ArrayList<>();
}
} catch (Exception ignore) {
}
try {
return new Gson().fromJson(json, typeOfT);
} catch (NumberFormatException e) {
return new ArrayList<>();
}
}
}
3.String适配器
package com.zhisheng.modulenetwork.typeadapter;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
public class MyStringAdapter implements JsonSerializer<String>, JsonDeserializer<String> {
@Override
public String deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
try {
if (json.getAsString().equals("") || json.getAsString().equals("null")) {//定义为long类型,如果后台返回""或者null,则返回0
return "";
}
} catch (Exception ignore) {
}
try {
return json.getAsString();
} catch (NumberFormatException e) {
return "";
}
}
@Override
public JsonElement serialize(String src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive (src);
}
}
4.比如boolean 类型 int类型 Long类型等等可自己实现
网友评论