Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...