1
0
mirror of synced 2026-10-07 23:39:43 +08:00

🎨 #4056 修复 GsonHelper 在读取数组属性时的健壮性问题

This commit is contained in:
Vasiliy Mikhailov
2026-07-10 17:27:36 +03:00
committed by GitHub
parent eeb37cd3ea
commit 6ca6c342aa
2 changed files with 29 additions and 4 deletions

View File

@@ -108,7 +108,7 @@ public class GsonHelper {
}
public static Integer[] getIntArray(JsonObject o, String string) {
JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string));
JsonArray jsonArray = getAsJsonArray(o.get(string));
if (jsonArray == null) {
return null;
}
@@ -122,7 +122,7 @@ public class GsonHelper {
}
public static String[] getStringArray(JsonObject o, String string) {
JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string));
JsonArray jsonArray = getAsJsonArray(o.get(string));
if (jsonArray == null) {
return null;
}
@@ -136,7 +136,7 @@ public class GsonHelper {
}
public static Long[] getLongArray(JsonObject o, String string) {
JsonArray jsonArray = getAsJsonArray(o.getAsJsonArray(string));
JsonArray jsonArray = getAsJsonArray(o.get(string));
if (jsonArray == null) {
return null;
}
@@ -150,7 +150,7 @@ public class GsonHelper {
}
public static JsonArray getAsJsonArray(JsonElement element) {
return element == null ? null : element.getAsJsonArray();
return (element == null || !element.isJsonArray()) ? null : element.getAsJsonArray();
}
/**

View File

@@ -136,4 +136,29 @@ public class GsonHelperTest {
System.out.println(GsonHelper.buildJsonObject(1, true, "jsonElement", new JsonObject()));
System.out.println(GsonHelper.buildJsonObject("num", 2, "string", "cde", "char", 'a', "bool", true));
}
/**
* If the JSON property exists but is NOT a JSON array (e.g. a plain string),
* getIntArray should return null gracefully rather than throwing ClassCastException.
*/
@Test
public void testGetIntArrayNonArrayProperty() {
JsonObject json = new JsonObject();
json.addProperty("items", "not-an-array");
assertThat(GsonHelper.getIntArray(json, "items")).isNull();
}
@Test
public void testGetStringArrayNonArrayProperty() {
JsonObject json = new JsonObject();
json.addProperty("items", 123);
assertThat(GsonHelper.getStringArray(json, "items")).isNull();
}
@Test
public void testGetLongArrayNonArrayProperty() {
JsonObject json = new JsonObject();
json.addProperty("items", "not-an-array");
assertThat(GsonHelper.getLongArray(json, "items")).isNull();
}
}