gpt4 book ai didi

java - 如何在Java中解码使用GSON创建的JSON文件?

转载 作者:行者123 更新时间:2023-12-02 03:03:49 26 4
gpt4 key购买 nike

我已经使用 gson 成功创建了一个 JSON 文件,但现在我想解析同一个文件,编码变得一团糟。

这是我用来读取 JSON 文件的代码:

BufferedReader jsonFile = new BufferedReader(new FileReader("file.json"));
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson(jsonFile, HashMap.class);

我似乎无法弄清楚如何确保以正确的方式解析文件。

例如,文件中的有效 JSON 代码:

{"paris":[[1485907200000,182184411,41274],[1485993600000,151646118,36697],"london":[[1485907200000,30200160,155827]}

...解析如下:

{"paris":[[1.4859072E12,1.82184411E8,41274.0],[1.4859936E12,1.51646118E8,36697.0],"london":[[1.4859072E12,3.020016E7,155827.0]}

这会弄乱代码的其余部分,因为长整型不再是长整型。

例如,如果我尝试打印出一个值,如下所示:

System.out.println(trafficInput.get("paris").get(0)[0]);

...我收到此错误:

Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to [J

有什么帮助吗?

最佳答案

发生这种情况是因为以下行:

trafficInput = gson.fromJson(jsonFile, HashMap.class);

此行指示 gson 将字符串反序列化为 HashMap,而不指定任何类型,因此,gson 应用其默认转换机制(即将 Number 转换为 double 等)。这就是 Sysout 语句导致 ClassCastException 的原因,因为该元素不是数组

您需要做的就是在调用 fromJson 方法时指定一个 TypeToken ,它将处理类型。例如:

Gson gson = new Gson();
Type type = new TypeToken<Map<String, List<long[]>>>(){}.getType();
Map<String, List<long[]>> trafficInput = new HashMap<>();
trafficInput = gson.fromJson("{\"paris\":[[1485907200000,182184411,41274],[1485993600000,151646118,36697]],\"london\":[[1485907200000,30200160,155827]]}", type);
System.out.println(trafficInput);
System.out.println(gson.toJson(trafficInput));

上面的代码片段打印没有科学记数法的数字。

关于java - 如何在Java中解码使用GSON创建的JSON文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42053708/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com