我试图在我的项目中调整GSON库。当我尝试读取JSON文件并将JSON字符串转换为JAVA对象时,会发生以下错误:
**com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.Gson.fromJson(Gson.java:900)
at Company.getAllCars(Company.java:39)
at Main.main(Main.java:12)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.Gson.fromJson(Gson.java:888)
... 2 more**
据我了解,这可能是我的.json文件的问题,但也许有人可以帮忙解决这个问题?下面你可以看到我的方法如何将JSON对象输出到文件以及我如何尝试读取该文件和我的.json文件。我将非常感谢你的帮助。谢谢!
public void buyCar(Car car){
Gson gson = new Gson();
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("CarList.json",true));
PrintWriter pw = new PrintWriter(bw);
String json = gson.toJson(car);
pw.println(json);
pw.close();
bw.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public LinkedList<Car> getAllCars(){
Gson gson = new Gson();
Type type = new TypeToken<LinkedList<Car>>(){}.getType();
LinkedList<Car> carList = new LinkedList<>();
try{
JsonReader reader = new JsonReader(new FileReader(carListName));
carList = gson.fromJson(reader,type);
}
catch (Exception e){
e.printStackTrace();
}
return carList;
}
CarList.json
{
"brand": "VW",
"year": 2018
}{
"brand": "BMW",
"year": 2018
}{
"brand": "Audi",
"year": 2018
}{
"brand": "Opel",
"year": 2018
}{
"brand": "Lambo",
"year": 2018
}