Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

解决请求成功和失败时服务器返回的data数据的结构不一样的问题(Gson自定义解析) #234

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
## 版本说明

### 当前版本
[![release](https://img.shields.io/badge/release-V2.1.2-orange.svg)](https://github.com/zhou-you/RxEasyHttp/blob/master/update.md)
[![release](https://img.shields.io/badge/release-V2.1.5-orange.svg)](https://github.com/zhou-you/RxEasyHttp/blob/master/update.md)

**[历史版本,点我、点我、点我>>](https://github.com/zhou-you/RxEasyHttp/blob/master/update.md)**

Expand All @@ -75,7 +75,7 @@
### build.gradle设置
```
dependencies {
compile 'com.zhouyou:rxeasyhttp:2.1.5'
implementation 'com.zhouyou:rxeasyhttp:2.1.5'
}
```
想查看所有版本,请点击下面地址。
Expand Down
30 changes: 14 additions & 16 deletions rxeasyhttp/build.gradle
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
apply plugin: 'com.android.library'
//apply plugin: 'me.tatarka.retrolambda'

android {
compileSdkVersion 23
buildToolsVersion '25.0.0'
compileSdkVersion 29
buildToolsVersion '30.0.2'

defaultConfig {
minSdkVersion 15
targetSdkVersion 23
targetSdkVersion 29
versionCode 4
versionName "2.1.6"

Expand All @@ -31,19 +30,18 @@ android {
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
api fileTree(include: ['*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
testImplementation 'junit:junit:4.13'
//第三方依赖库
compile 'com.squareup.okhttp3:logging-interceptor:3.12.2'
compile 'com.squareup.okhttp3:okhttp:3.12.2'
compile 'com.jakewharton:disklrucache:2.0.2'
compile 'io.reactivex.rxjava2:rxjava:2.2.10'
compile 'io.reactivex.rxjava2:rxandroid:2.1.1'
compile 'com.squareup.retrofit2:retrofit:2.5.0'
compile 'com.squareup.retrofit2:converter-gson:2.5.0'
compile 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
api 'com.squareup.okhttp3:logging-interceptor:3.12.2'
api 'com.squareup.okhttp3:okhttp:3.12.2'
api 'com.jakewharton:disklrucache:2.0.2'
api 'io.reactivex.rxjava2:rxjava:2.2.10'
api 'io.reactivex.rxjava2:rxandroid:2.1.1'
api 'com.squareup.retrofit2:retrofit:2.5.0'
api 'com.squareup.retrofit2:converter-gson:2.5.0'
api 'com.squareup.retrofit2:adapter-rxjava2:2.5.0'
}
apply from: '../bintray.gradle'
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializer;
import com.google.gson.JsonSyntaxException;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.R;
import com.zhouyou.http.model.ApiResult;

import org.apache.http.conn.ConnectTimeoutException;
Expand Down Expand Up @@ -121,39 +123,40 @@ public static ApiException handleException(Throwable e) {
|| e instanceof NotSerializableException
|| e instanceof ParseException) {
ex = new ApiException(e, ERROR.PARSE_ERROR);
ex.message = "解析错误";

ex.message = EasyHttp.getContext().getString(R.string.parsing_error);
return ex;
} else if (e instanceof ClassCastException) {
ex = new ApiException(e, ERROR.CAST_ERROR);
ex.message = "类型转换错误";
ex.message = EasyHttp.getContext().getString(R.string.type_conversion_error);
return ex;
} else if (e instanceof ConnectException) {
ex = new ApiException(e, ERROR.NETWORD_ERROR);
ex.message = "连接失败";
ex.message = EasyHttp.getContext().getString(R.string.connection_failed);
return ex;
} else if (e instanceof javax.net.ssl.SSLHandshakeException) {
ex = new ApiException(e, ERROR.SSL_ERROR);
ex.message = "证书验证失败";
ex.message = EasyHttp.getContext().getString(R.string.certificate_verification_failed);
return ex;
} else if (e instanceof ConnectTimeoutException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "连接超时";
ex.message = EasyHttp.getContext().getString(R.string.time_out);
return ex;
} else if (e instanceof java.net.SocketTimeoutException) {
ex = new ApiException(e, ERROR.TIMEOUT_ERROR);
ex.message = "连接超时";
ex.message = EasyHttp.getContext().getString(R.string.time_out);
return ex;
} else if (e instanceof UnknownHostException) {
ex = new ApiException(e, ERROR.UNKNOWNHOST_ERROR);
ex.message = "无法解析该域名";
ex.message = EasyHttp.getContext().getString(R.string.cannot_be_resolved);
return ex;
} else if (e instanceof NullPointerException) {
ex = new ApiException(e, ERROR.NULLPOINTER_EXCEPTION);
ex.message = "NullPointerException";
return ex;
} else {
ex = new ApiException(e, ERROR.UNKNOWN);
ex.message = "未知错误";
ex.message = EasyHttp.getContext().getString(R.string.unknown_error);
return ex;
}
}
Expand Down
239 changes: 134 additions & 105 deletions rxeasyhttp/src/main/java/com/zhouyou/http/func/ApiResultFunc.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,12 @@

package com.zhouyou.http.func;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zhouyou.http.gson.ZGsonBuilder;
import com.zhouyou.http.model.ApiResult;
import com.zhouyou.http.utils.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
Expand All @@ -43,114 +34,152 @@
* 日期: 2017/3/15 16:52 <br>
* 版本: v1.0<br>
*/
@SuppressWarnings("unchecked")
public class ApiResultFunc<T> implements Function<ResponseBody, ApiResult<T>> {
protected Type type;
protected Gson gson;

public ApiResultFunc(Type type) {
gson = new GsonBuilder()
.excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
.serializeNulls()
.create();
this.type = type;
gson = ZGsonBuilder.gsonBuilder2(type).create();
}

@Override
public ApiResult<T> apply(@NonNull ResponseBody responseBody) throws Exception {
public ApiResult<T> apply(@NonNull ResponseBody responseBody) {
ApiResult<T> apiResult = new ApiResult<>();
apiResult.setCode(-1);
if (type instanceof ParameterizedType) {//自定义ApiResult
final Class<T> cls = (Class) ((ParameterizedType) type).getRawType();
if (ApiResult.class.isAssignableFrom(cls)) {
final Type[] params = ((ParameterizedType) type).getActualTypeArguments();
final Class clazz = Utils.getClass(params[0], 0);
final Class rawType = Utils.getClass(type, 0);
try {
String json = responseBody.string();
//增加是List<String>判断错误的问题
if (!List.class.isAssignableFrom(rawType) && clazz.equals(String.class)) {
apiResult.setData((T) json);
apiResult.setCode(0);
/* final Type type = Utils.getType(cls, 0);
ApiResult result = gson.fromJson(json, type);
if (result != null) {
apiResult = result;
apiResult.setData((T) json);
} else {
apiResult.setMsg("json is null");
}*/
} else {
ApiResult result = gson.fromJson(json, type);
if (result != null) {
apiResult = result;
} else {
apiResult.setMsg("json is null");
}
}
} catch (Exception e) {
e.printStackTrace();
apiResult.setMsg(e.getMessage());
} finally {
responseBody.close();
}
} else {
apiResult.setMsg("ApiResult.class.isAssignableFrom(cls) err!!");
}
} else {//默认Apiresult
try {
final String json = responseBody.string();
final Class<T> clazz = Utils.getClass(type, 0);
if (clazz.equals(String.class)) {
//apiResult.setData((T) json);
//apiResult.setCode(0);
final ApiResult result = parseApiResult(json, apiResult);
if (result != null) {
apiResult = result;
apiResult.setData((T) json);
} else {
apiResult.setMsg("json is null");
}
} else {
final ApiResult result = parseApiResult(json, apiResult);
if (result != null) {
apiResult = result;
if (apiResult.getData() != null) {
T data = gson.fromJson(apiResult.getData().toString(), clazz);
apiResult.setData(data);
} else {
apiResult.setMsg("ApiResult's data is null");
}
} else {
apiResult.setMsg("json is null");
}
}
} catch (JSONException e) {
e.printStackTrace();
apiResult.setMsg(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
apiResult.setMsg(e.getMessage());
} finally {
responseBody.close();
}
}
return apiResult;
}

private ApiResult parseApiResult(String json, ApiResult apiResult) throws JSONException {
if (TextUtils.isEmpty(json))
return null;
JSONObject jsonObject = new JSONObject(json);
if (jsonObject.has("code")) {
apiResult.setCode(jsonObject.getInt("code"));
}
if (jsonObject.has("data")) {
apiResult.setData(jsonObject.getString("data"));
}
if (jsonObject.has("msg")) {
apiResult.setMsg(jsonObject.getString("msg"));
try {
String json = responseBody.string();
return gson.fromJson(json, type);
} catch (IOException e) {
e.printStackTrace();
apiResult.setMsg(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
apiResult.setMsg(e.getMessage());
} finally {
responseBody.close();
}

return apiResult;
}

}




///*
// * Copyright (C) 2017 zhouyou(478319399@qq.com)
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package com.zhouyou.http.func;
//
//import android.text.TextUtils;
//
//import com.google.gson.Gson;
//import com.google.gson.GsonBuilder;
//import com.zhouyou.http.model.ApiResult;
//import com.zhouyou.http.utils.Utils;
//
//import org.json.JSONException;
//import org.json.JSONObject;
//
//import java.io.IOException;
//import java.lang.reflect.Modifier;
//import java.lang.reflect.Type;
//import java.util.List;
//
//import io.reactivex.annotations.NonNull;
//import io.reactivex.functions.Function;
//import okhttp3.ResponseBody;
//
//
///**
// * <p>描述:定义了ApiResult结果转换Func</p>
// * 作者: zhouyou<br>
// * 日期: 2017/3/15 16:52 <br>
// * 版本: v1.0<br>
// */
//@SuppressWarnings("unchecked")
//public class ApiResultFunc<T> implements Function<ResponseBody, ApiResult<T>> {
// protected Type type;
// protected Gson gson;
//
// public ApiResultFunc(Type type) {
// gson = new GsonBuilder()
// .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
// .serializeNulls()
// .create();
// this.type = type;
// }
//
// @Override
// public ApiResult<T> apply(@NonNull ResponseBody responseBody) {
// ApiResult<T> apiResult = new ApiResult<>();
// apiResult.setCode(-1);
//
// try {
// String json = responseBody.string();
// final ApiResult result = parseApiResult(json, apiResult);
//
// if (result == null) {
// apiResult.setMsg("data is null");
// } else {
// apiResult.setCode(result.getCode());
// apiResult.setMsg(result.getMsg());
//
// final Class<T> clazz = Utils.getClass(type, 0);
// //增加是List<String>判断错误的问题
// if (apiResult.isOk()) {
// if (!List.class.isAssignableFrom(clazz) && clazz.equals(String.class)) {
// apiResult.setData((T) json);
// apiResult.setCode(0);
// } else {
// apiResult = gson.fromJson(json, type);
// }
// }
// }
// } catch (JSONException e) {
// e.printStackTrace();
// apiResult.setMsg(e.getMessage());
// } catch (IOException e) {
// e.printStackTrace();
// apiResult.setMsg(e.getMessage());
// } catch (Exception e) {
// e.printStackTrace();
// apiResult.setMsg(e.getMessage());
// } finally {
// responseBody.close();
// }
// return apiResult;
// }
//
// private ApiResult parseApiResult(String json, ApiResult apiResult) throws JSONException {
// if (TextUtils.isEmpty(json))
// return null;
// JSONObject jsonObject = new JSONObject(json);
// if (jsonObject.has("code")) {
// apiResult.setCode(jsonObject.getInt("code"));
// }
// if (jsonObject.has("message")) {
// apiResult.setMsg(jsonObject.getString("message"));
// }
//// if (jsonObject.has("data")) {
//// apiResult.setData(jsonObject.getString("data"));
//// }
// return apiResult;
// }
//}
Loading