一、配置
//RxJava/RxAndroid
compile'io.reactivex.rxjava2:rxjava:2.0.1'
compile'io.reactivex.rxjava2:rxandroid:2.0.1'
//retrofit
compile'com.squareup.retrofit2:retrofit:2.1.0'
//Gson converter
compile'com.squareup.retrofit2:converter-gson:2.1.0'
/* compile('org.ligboy.retrofit2:converter-fastjson:2.1.0') {
exclude module: 'fastjson'
}*/
//RxJava2 Adapter
compile'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//okhttp
compile'com.squareup.okhttp3:okhttp:3.4.1'
compile'com.squareup.okhttp3:logging-interceptor:3.4.1'
二、服务器返回格式
{
error:"0",
content:{},
message:"success"
}
三、定义Bean
public class HttpResult{
private String message;
private String error;
private String content;//相关数据
}
四、API
@FormUrlEncoded
@POST("mobile/user/login")
Observable<HttpResult> login(@Field("key")String key,@Field("imei")String imei,@Field("isInit")String isInit);
五、运行抛异常
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 3 column 16 path $.content
六、泛型问题
将HttpResult改成
public class HttpResult<T>{
private String message;
private String error;
private T content;//相关数据
}
将Api改成
@FormUrlEncoded
@POST("mobile/user/login")
Observable<HttpResult<User>> login(@Field("key")String key,@Field("imei")String imei,@Field("isInit")String isInit);
运行抛异常**
com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: Invalid double: ""**
尝试以下配置依旧抛异常
GsonBuilder gsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss");**
gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
gsonBuilder.serializeNulls();
Gson gson = gsonBuilder.create();
七、泛型不确定类型 抛异常
[泛型解析遇到com.google.gson.internal.LinkedTreeMap cannot be cast to object]
八、临时解决办法
将compile'com.squareup.retrofit2:retrofit:2.1.0' //Gson converter
换成
compile'com.squareup.retrofit2:converter-gson:2.1.0' //fastjson 可以解决
九、再此望各位有解决办法的不吝指教!万分感谢!!
十、(20170405补充)已找问题所在,是由于服务器返回的是非标准Gson格式(包含换行符)
解决办法1.参考八;2.返回Responsebody自行解析;3.让服务器修改返回标准Gson字符串格式