Google Gson 将每个 JSON 本地文件视为字符串,即使它不是 [英] Google Gson treats every JSON local file as a string even when its not

查看:20
本文介绍了Google Gson 将每个 JSON 本地文件视为字符串,即使它不是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不断收到 预期的 BEGIN_TYPE 但在第 1 行第 1 列路径 $ 处出现 STRING 错误.我已了解该错误,但我遇到了不同的情况.

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

这也能编译.

我的问题是当我尝试从我自己编写或从网上下载的本地文件中读取时(我已经在 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 时,它可以工作.但是,如果我从本地文件运行相同的 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 本地文件视为字符串,即使它不是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆