一、配置
//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'
二、服務(wù)器返回格式
{
error:"0",
content:{},
message:"success"
}
三、定義Bean
public class HttpResult{
private String message;
private String error;
private String content;//相關(guān)數(shù)據(jù)
}
四、API
@FormUrlEncoded
@POST("mobile/user/login")
Observable<HttpResult> login(@Field("key")String key,@Field("imei")String imei,@Field("isInit")String isInit);
五、運(yùn)行拋異常
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;//相關(guān)數(shù)據(jù)
}
將Api改成
@FormUrlEncoded
@POST("mobile/user/login")
Observable<HttpResult<User>> login(@Field("key")String key,@Field("imei")String imei,@Field("isInit")String isInit);
運(yùn)行拋異常**
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補(bǔ)充)已找問題所在,是由于服務(wù)器返回的是非標(biāo)準(zhǔn)Gson格式(包含換行符)
解決辦法1.參考八;2.返回Responsebody自行解析;3.讓服務(wù)器修改返回標(biāo)準(zhǔn)Gson字符串格式