问题描述
我不断收到Expected BEGIN_TYPE but was STRING at line 1 column 1 path $
错误.我已经读过有关该错误的信息,但是遇到了一些不同的情况.
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.
当我尝试在我在应用程序中创建的JSON
字符串上使用gson.fromJson()
时,它可以很好地编译.
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);
这会编译.
Type carList = new TypeToken<ArrayList<MyCar>>(){}.getType();
ArrayList<MyCar> myCars = gson.fromJson(json, carList);
这也可以编译.
我的问题是,当我尝试读取自己写的本地文件或从Web下载的本地文件时(我已经在JsonLint
上运行了所有本地文件,并且它们是有效的).
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).
这是写入名为testingArray.json
的文件时的JSON:
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.
但是这个:
Type carList = new TypeToken<ArrayList<MyCar>>(){}.getType();
ArrayList<MyCar> myCars = gson.fromJson(basePath + "testingArray.json", carList);
不编译并给出上述错误.
Doesn't compile and gives the aforementioned error.
为什么我傻眼了,因为当我在JSON
之类的POJO
上运行fromJson
时,它可以工作.但是,如果我从本地文件运行SAME JSON数据,它将无法正常工作.即使它以方括号开头,它也始终将其读取为字符串.
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.
推荐答案
指向文件的路径在字面上被视为JSON
有效负载,因此这就是为什么您看到此异常的原因.您需要根据文件的路径创建Reader
:
Path to the file is treated literally as JSON
payload, so this why you see this exception. You need to create Reader
based on path to the file:
try (FileReader jsonReader = new FileReader(basePath + "testingArray.json")) {
Type carList = new TypeToken<ArrayList<MyCar>>(){}.getType();
List<MyCar> myCars = gson.fromJson(jsonReader, carList);
}
这篇关于Google Gson会将每个JSON本地文件都视为字符串,即使不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!