如何使用 gson 解析 json 文件?

How do I parse a json file using gson?

我正在尝试使用 gson 从大型 json 文件中读取某些行。问题是我写的代码不会解析 utf-8 编码。

Gson gson = new Gson();
    Items[] myItems = gson.fromJson(new FileReader("./input/raw-1.json"), Items[].class);
    System.out.println(gson.toJson(myItems));

Gson gson2 = new GsonBuilder().setPrettyPrinting().create();
    Writer writer = Files.newBufferedWriter(Paths.get("./output/output-sample-test.json"));
    gson2.toJson(myItems, writer);
    writer.close();

class Items {
    long id;
    int dayId;
    String clientAddress;
    String pickupAddress;
    String venueName;
    String pickupTime;
    double pickupLat;
    double pickupLon;
    double deliveryLat;
    double deliveryLon;
}

它会输出这些奇怪的符号:

"clientAddress": "Timisoara, Strada Gheorghe Lazăr nr. 24, bloc Fructus Plaza, ap. 22, et. 7"

我做错了什么?顺便说一句,对不起我的英语不好。谢谢!

JSON 应该以 UTF-8 编码。 FileReader 假设文件是​​用您系统的文本文件默认编码编码的,这可能不是 UTF-8。如果你使用 Files.newBufferedReader 你可以指定编码:

try (Reader reader = Files.newBufferedReader(Paths.get("./input/raw-1.json"), StandardCharsets.UTF_8)) {
    Items[] myItems = gson.fromJson(reader, Items[].class);
}

同样,写的时候要指定编码:

try (Writer writer = Files.newBufferedWriter(Paths.get("./output/output-sample-test.json", StandardCharsets.UTF_8)) {
    gson2.toJson(myItems, writer);
}