You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Gson解析API返回的嵌套JSON数组?

Fixing JsonSyntaxException When Parsing Nested JSON Arrays with Gson

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 id field in ResultType to a String
  • Add a custom type adapter or use @JsonAdapter to handle the string-to-int conversion explicitly

内容的提问来源于stack exchange,提问作者Lincoln

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:31:54