I am constantly getting Expected BEGIN_TYPE but was STRING at line 1 column 1 path $
error. I've read about that error, but I am experiencing something different.
When I try to use gson.fromJson()
on a JSON
string I've created in my app it compiles fine.
ArrayList<MyCar> cars = new ArrayList<>();
cars.add(new MyCar());
cars.add(new MyCar());
String json = gson.toJson(cars);
This compiles.
Type carList = new TypeToken<ArrayList<MyCar>>(){}.getType();
ArrayList<MyCar> myCars = gson.fromJson(json, carList);
This compiles as well.
My problem is when I try to read from a local file I've either written myself or downloaded from the web (I have run all local files on JsonLint
and they're valid).
Here is the JSON when written to a file named testingArray.json
:
[{
"model": "I3",
"manufacturer": "Audi",
"features": ["wifi", "bluetooth", "charging"]
}, {
"model": "I3",
"manufacturer": "Audi",
"features": ["wifi", "bluetooth", "charging"]
}, {
"model": "I3",
"manufacturer": "Audi",
"features": ["wifi", "bluetooth", "charging"]
}]
It clearly begins with brackets and not quotes.
But this:
Type carList = new TypeToken<ArrayList<MyCar>>(){}.getType();
ArrayList<MyCar> myCars = gson.fromJson(basePath + "testingArray.json", carList);
Doesn't compile and gives the aforementioned error.
I am dumbfounded as to why, because when I run fromJson
on a POJO
like JSON
it works. But if I run the SAME JSON data from a local file it doesn't work. It always reads it as a string even if it begins with brackets.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…