Skip to content

Commit

Permalink
Gson反序列化为null时,抛出异常
Browse files Browse the repository at this point in the history
  • Loading branch information
liujingxing committed Mar 31, 2022
1 parent 31b6fb9 commit 58b7453
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 4 deletions.
7 changes: 5 additions & 2 deletions rxhttp/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,8 @@ dependencies {
api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
}

sourceCompatibility = "8"
targetCompatibility = "8"

java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonWriter;
Expand Down Expand Up @@ -53,7 +54,11 @@ public <T> T convert(ResponseBody body, @NonNull Type type, boolean needDecodeRe
result = RxHttpPlugins.onResultDecoder(result);
}
if (type == String.class) return (T) result;
return gson.fromJson(result, type);
T t = gson.fromJson(result, type);
if (t == null) {
throw new JsonSyntaxException("The string '" + result + "' could not be deserialized to " + type + " object");
}
return t;
} finally {
body.close();
}
Expand Down
6 changes: 5 additions & 1 deletion rxhttp/src/main/java/rxhttp/wrapper/utils/GsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ public static <T> T getObject(String json, Type type) {
@NonNull
public static <T> T fromJson(String json, Type type) {
Gson gson = buildGson();
return gson.fromJson(json, type);
T t = gson.fromJson(json, type);
if (t == null) {
throw new JsonSyntaxException("The string '" + json + "' could not be deserialized to " + type + " object");
}
return t;
}

public static String toJson(Object object) {
Expand Down

0 comments on commit 58b7453

Please sign in to comment.