Google Gson treats every JSON local file as a string even when its not

落爺英雄遲暮 提交于 2021-02-02 09:55:39

问题


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.


回答1:


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); 
}


来源:https://stackoverflow.com/questions/55791761/google-gson-treats-every-json-local-file-as-a-string-even-when-its-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!