GSON解析报错:Expected BEGIN_ARRAY but was BEGIN_OBJECT 问题求助
Hey there! I’ve run into this exact GSON issue before, so let’s get it sorted out for you. That error message is telling you exactly what’s wrong: GSON was expecting a JSON array (starting with [) at the root of your file, but instead it found a JSON object (starting with {). This almost always boils down to a mismatch between your Java model classes and the structure of your JSON file.
Let’s Break Down the Problem
Let’s assume your CarList.json looks something like this (a super common scenario):
{
"cars": [
{"make": "Toyota", "model": "Camry", "year": 2024},
{"make": "Honda", "model": "Civic", "year": 2023}
]
}
If you’re trying to parse this directly into a List<Car> or Car[] using code like this:
Gson gson = new Gson(); List<Car> carList = gson.fromJson(jsonFileContent, new TypeToken<List<Car>>(){}.getType());
Gson will throw that error because the root of your JSON is an object (with a cars key), not a raw array.
The Fixes
You have two straightforward options to resolve this:
Option 1: Create a Wrapper Class for Your JSON Object
Match your Java model to the JSON’s structure by creating a wrapper class that holds the list of cars:
public class CarListWrapper { // Make sure the field name matches the key in your JSON exactly, or use @SerializedName if needed private List<Car> cars; // Add getters and setters public List<Car> getCars() { return cars; } public void setCars(List<Car> cars) { this.cars = cars; } }
Then parse using this wrapper class instead:
Gson gson = new Gson(); CarListWrapper wrapper = gson.fromJson(jsonFileContent, CarListWrapper.class); List<Car> carList = wrapper.getCars();
Option 2: Adjust Your JSON to Be a Root Array
If your intention was to have a raw array of cars, modify CarList.json to start and end with brackets instead of curly braces:
[
{"make": "Toyota", "model": "Camry", "year": 2024},
{"make": "Honda", "model": "Civic", "year": 2023}
]
Now your original code to parse into aList<Car>will work perfectly.
Quick Checks to Avoid Future Issues
- Double-check that your JSON has no syntax errors (missing commas, unclosed brackets/braces can cause weird parsing issues)
- Use
@SerializedName("json_key_name")on your Java fields if the JSON key names don’t match your Java field names (e.g., JSON usescar_modelbut your Java field iscarModel) - When writing the JSON to file, confirm that the structure you’re writing matches what you expect to parse later
内容的提问来源于stack exchange,提问作者Deividito

