🎨 #4056 修复 GsonHelper 在读取数组属性时的健壮性问题
This commit is contained in:
committed by
GitHub
parent
eeb37cd3ea
commit
6ca6c342aa
@@ -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();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user