项目开发的时候,有同事遇到了一个Gson解析的异常,原因是Base64字符串中有空格造成的
1、修改前
/**
* 获取Retrofit设置
* @param ctx 上下文
* @param serverUrl 请求地址
* @param certificateIn 证书文件流
* @param certificatePwd 证书密码
* @return retrofit
*/
protected Retrofit getRetrofit(Context ctx, String serverUrl, InputStream certificateIn, String certificatePwd) {
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(serverUrl);
builder.client(genericClient(ctx, serverUrl, certificateIn, certificatePwd));
builder.validateEagerly(true);
builder.addConverterFactory(GsonConverterFactory.create(gson));
builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
return builder.build();
}
2、修改后
/**
* 获取Retrofit设置
* @param ctx 上下文
* @param serverUrl 请求地址
* @param certificateIn 证书文件流
* @param certificatePwd 证书密码
* @return retrofit
*/
protected Retrofit getRetrofit(Context ctx, String serverUrl, InputStream certificateIn, String certificatePwd) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl(serverUrl);
builder.client(genericClient(ctx, serverUrl, certificateIn, certificatePwd));
builder.validateEagerly(true);
builder.addConverterFactory(GsonConverterFactory.create(gson));
builder.addCallAdapterFactory(RxJavaCallAdapterFactory.create());
return builder.build();
}
3、修改关键处
Gson gson = new GsonBuilder()
.setLenient()
.create();