一般来讲服务器返回的接口数据都是一种格式,通常使用
.addConverterFactory ( GsonConverterFactory.create ( ) )
即可正常解析并接收到返回结果。但是,请看以下2中返回结果,我暂且将该功能定义为获取用户列表。
这只是其中一种返回形式,为了更加方便接收各种各样的数据,接收的实体类这样写
public class ApiResponse<T>{
int code;
String message;
T data;
}
当你在IService.class的接口类声明中这样写,当接口返回的内容跟【图1】所示时,是正常执行的
Observable< ApiResponse< List<User>> > getUsers();
但是,当服务器返回以下数据,就会报错了
java.lang.IllegalStateException:
Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 91 path $.data
解决办法
1.自定义一个factory:MyConverterFactory.class
public class MyConverterFactory extends Converter.Factory {
public static MyConverterFactory create ( ) {
return create ( new Gson ( ) );
}
public static MyConverterFactory create ( Gson gson ) {
if ( gson == null ) {
throw new NullPointerException ( "gson == null" );
}
return new MyConverterFactory ( gson );
}
private final Gson gson;
private MyConverterFactory ( Gson gson ) {
this.gson = gson;
}
@Override
public Converter< ResponseBody, ? > responseBodyConverter ( @NonNull Type type,
@NonNull Annotation[] annotations,
@NonNull Retrofit retrofit ) {
return new MyResponseBodyConverter<> ( gson, type );
}
@Override
public Converter< ?, RequestBody > requestBodyConverter ( @NonNull Type type,
@NonNull Annotation[] parameterAnnotations,
@NonNull Annotation[] methodAnnotations,
@NonNull Retrofit retrofit ) {
TypeAdapter< ? > adapter = gson.getAdapter ( TypeToken.get ( type ) );
return new MyRequestBodyConverter<> ( gson, adapter );
}
}
2.自定义响应解析器
在这种情况下,当服务器返回有内容的列表数据,解析器正常转换。没有数据或请求不成功时,data字段转换成List肯定会失败("["不存在),所以会抛出异常,在异常中去处理即可
final class MyResponseBodyConverter< T > implements Converter< ResponseBody, T > {
private final Gson gson;
private final Type type;
MyResponseBodyConverter ( Gson gson, Type type ) {
this.gson = gson;
this.type = type;
}
@Override
public T convert ( @NonNull ResponseBody value ) {
String str = "";
try {
if ( value.contentLength ( ) != 0 ) {
str = value.source ( ).readUtf8 ( );
return convert ( str, type );
} else {
str = "{\"code\":90000,\"message\":\"服务器无响应\"}";
return convert ( str, CallResult.class );
}
} catch ( Exception e ) {
Logger.e ( "使用第二种转换方法:" + e.getMessage ( ) );
return convert ( str, CallResult.class );
} finally {
value.close ( );
}
}
private T convert ( String orgData, Type type ) {
if ( TextUtils.isEmpty ( orgData ) ) {
return null;
}
if ( type == null ) {
return null;
}
return gson.fromJson ( orgData, type );
}
}
3.自定义请求体解析器
final class MyRequestBodyConverter< T > implements Converter< T, RequestBody > {
private static final MediaType MEDIA_TYPE = MediaType.get ( "application/json; charset=UTF-8" );
private static final Charset UTF_8 = StandardCharsets.UTF_8;
private final Gson gson;
private final TypeAdapter< T > adapter;
MyRequestBodyConverter ( Gson gson, TypeAdapter< T > adapter ) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert ( @NonNull T value ) throws IOException {
Buffer buffer = new Buffer ( );
Writer writer = new OutputStreamWriter ( buffer.outputStream ( ), UTF_8 );
JsonWriter jsonWriter = gson.newJsonWriter ( writer );
adapter.write ( jsonWriter, value );
jsonWriter.close ( );
return RequestBody.create ( MEDIA_TYPE, buffer.readByteString ( ) );
}
}
至此,解析错误的问题已经得到解决。
附
一般使用rxjava都会用一个拦截器来查看接口调用情况以便开发,但responsebody度过一次后却不能再读,导致转换器转换是拿到的数据为空,解决办法如下(原理就是新建一个body,填充一模一样的数据进去)
rxjava日志拦截器MyLogInterceptor
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Interceptor.Chain;
import okhttp3.Response.Builder;
import okio.Buffer;
import okio.BufferedSource;
import retrofit2.internal.EverythingIsNonNull;
@EverythingIsNonNull
public class LogInterceptor implements Interceptor {
private static final Charset UTF8;
private static final int CUT_LENGTH = 500;
private static final String BODY_SUCCESS_FLAG1 = "\"code\":200";
private static final String BODY_SUCCESS_FLAG2 = "\"Result\":true";
public LogInterceptor() {
}
public Response intercept(Chain chain) throws IOException {
Response response = null;
Request request = chain.request();
try {
RequestBody requestBody = request.body();
String body = null;
if (requestBody != null) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
assert charset != null;
body = buffer.readString(charset);
}
response = chain.proceed(request);
ResponseBody responseBody = response.body();
String rBody = "";
assert responseBody != null;
BufferedSource source = responseBody.source();
source.request(9223372036854775807L);
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException var15) {
var15.printStackTrace();
}
}
if (charset != null) {
rBody = buffer.clone().readString(charset);
}
String shortUrl = response.request().url().toString();
shortUrl = shortUrl.substring(shortUrl.length() / 2);
StringBuilder sb = new StringBuilder(shortUrl);
if (!rBody.contains("\"code\":200") && !rBody.contains("\"Result\":true")) {
sb.append("---->请求失败!");
} else {
sb.append("---->请求成功!");
}
sb.append("\n▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁");
sb.append("\n【请求响应码】").append(response.code());
sb.append("\n【请求路径】").append(response.request().url());
sb.append("\n【请求方法】").append(request.method());
String headers = request.headers().toString();
sb.append("\n【请求头】headers.length=").append(headers.length());
if (body != null) {
if (body.length() <= 500) {
sb.append("\n【请求参数】").append(body);
} else {
sb.append("\n【请求参数】").append(body.substring(0, 500)).append("...");
}
} else {
sb.append("\n【请求参数】无");
}
sb.append("\n【请求回调】").append(rBody);
sb.append("\n▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔");
Logger.d(shortUrl, sb.toString());
return response;
} catch (IOException var16) {
Logger.e("MyLogInterceptor的错误:" + var16.getMessage());
return chain.proceed(request);
}
}
static {
UTF8 = StandardCharsets.UTF_8;
}
}