Retrofit 关于Gson 碰到坑求救

一、配置
//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字符串格式

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,087评论 25 709
  • 新项目由自己重头架构,因此使用MVP模式,库的使用上使用了Rxjava 2.0,OkHttp 3.0,Retr...
    残霜丶阅读 3,502评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • 2015的冬天,在我把自己关进房子的很多天后,父亲带我去了医院-抑郁症。没有人意外,这是我们早在心里就确定过的结论...
    梅阿查阅读 2,532评论 0 0
  • 2017/4/22成长小组,来了一位新朋友A,刚见到她的时候觉得她开朗,利落,干脆,能干。熟悉了环境之后,她开始讲...
    VivyYNSH阅读 3,744评论 0 0