如何使用Gson解析API返回的嵌套JSON数组?
Let's break down what's going on here first: Your JSON is a nested array structure—it's an outer array where each element is another array containing a single ResultType object. The issue with your original code is that you tried to parse this into a single-level ArrayList<ResultType> or ResultType[], which doesn't match the JSON's hierarchy. That's why you're getting the Expected BEGIN_OBJECT but was BEGIN_ARRAY error—Gson was expecting to read an object for each element in the top-level array, but instead hit another array.
Solution 1: Parse into a Nested List (List<List<ResultType>>)
Adjust your TypeToken to match the nested structure of the JSON:
Type nestedResultListType = new TypeToken<ArrayList<ArrayList<ResultType>>>(){}.getType(); List<List<ResultType>> resultObj = new Gson().fromJson(result, nestedResultListType);
To access the actual ResultType objects, you'll need to iterate through the outer list and grab the first element of each inner list (since each inner array only has one item):
for(List<ResultType> innerList : resultObj) { if(!innerList.isEmpty()) { ResultType person = innerList.get(0); // Work with the person object here, e.g. person.getId() } }
Solution 2: Parse into a 2D Array (ResultType[][])
If you prefer working with arrays instead of lists, you can directly parse into a two-dimensional array:
ResultType[][] resultObj = new Gson().fromJson(result, ResultType[][].class);
Then iterate through it like this:
for(ResultType[] innerArray : resultObj) { if(innerArray.length > 0) { ResultType person = innerArray[0]; // Do something with the person object } }
Quick Side Note
Your ResultType class has an int id field, but the JSON uses string values for id (like "1"). Gson will automatically convert these strings to integers by default, but this could cause errors if the JSON ever includes a non-numeric id value. For better robustness, you could either:
- Change the
idfield inResultTypeto aString - Add a custom type adapter or use
@JsonAdapterto handle the string-to-int conversion explicitly
内容的提问来源于stack exchange,提问作者Lincoln

