我遇到了一个我不明白的奇怪问题。我正在开发一个 Java 程序,该程序使用 Steam API 来获取 Dota 2 统计数据。
for (int i = 0; i < MAX_REQUESTS; i++) {
competitiveMatches.addAll(getByStartTime(startTime));
System.out.println("Time: " + competitiveMatches.get(competitiveMatches.size() - 1).getStartTime());
startTime = competitiveMatches.get(competitiveMatches.size() - 1).getStartTime();
}
我在 System.out.println(...)
行收到错误消息:
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long
这对我来说没有任何意义,我正在请求列表中的最后一个匹配项,并访问其 start_time
变量,这是下面的方法。它的工作原理是查看 JSON Map 并获取该位置的值。
@Override
public long getStartTime() {
return (Long) jsonMap.get(KEY_START_TIME);
}
完整的堆栈跟踪:
Exception in thread "main" java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long
at de.inkvine.dota2stats.domain.impl.MatchOverviewImpl.getStartTime(MatchOverviewImpl.java:48)
at Silicon.main(Silicon.java:34)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
哪里
MatchOverviewImpl.java:48
是getStartMethod()
的返回Silicon.java:34
是System.out.println()
行
请求示例,match_id
、match_seq_num
和 start_time
全部存储为 double ,例如1.929962146E9
:
{
"match_id":1929981128,
"match_seq_num":1705354677,
"start_time":1447289804,
"lobby_type":8,
"radiant_team_id":0,
"dire_team_id":0,
"players":[
{
"account_id":82228820,
"player_slot":0,
"hero_id":19
},
{
"account_id":4294967295,
"player_slot":128,
"hero_id":14
}
]
}
最佳答案
您正在尝试通过转换将 Double
转换为 long
,但这是不可能的。您可以通过调用 longValue
将 Double
转换为其 long
对应项。 :
@Override
public long getStartTime() {
return jsonMap.get(KEY_START_TIME).longValue();
}
这是因为在 JSON 中,就像 JavaScript 一样,all numbers are floating point numbers (嗯, the spec doesn't make any distinction ),因此您使用的 JSON 库很可能会返回 Double
对象,无论数字是否有小数部分。
关于java - 将 double 转换为 long 时发生转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33662641/