【问题标题】:NumberFormatException while parsing a JSON String containing Long value解析包含 Long 值的 JSON 字符串时出现 NumberFormatException
【发布时间】:2018-05-26 14:11:47
【问题描述】:

我有一个日志文件,每个句子都包含一个 JSON 对象,如下所示:-

{"action": "follow", "target": "FabianoCaruana", "timestamp": 1487149397523, "user": "GMHikaru"}
{"action": "tweet", "id": 16606634614844517897, "message": "woop #ruby", "timestamp": 1487149445603, "user": "hugopeixoto"}
{"action": "retweet", "target_id": 16606634614844517897, "timestamp": 1487149446020, "user": "spambot"}
{"action": "retweet", "target_id": 16606634614844517897, "timestamp": 1487149446592, "user": "noob_saibot"}
{"action": "tweet", "id": 14936153188153171323, "message": "woop #vim", "timestamp": 1487149463067, "user": "eevee"}
{"action": "follow", "target": "eevee", "timestamp": 1487149466209, "user": "pkoch"}
{"action": "tweet", "id": 1801829421162967878, "message": "woop #processes", "timestamp": 1487149468671, "user": "r00k"}
{"action": "retweet", "target_id": 1801829421162967878, "timestamp": 1487149469555, "user": "noob_saibot"}
{"action": "follow", "target": "r00k", "timestamp": 1487149472418, "user": "pkoch"}

我正在使用 JSON 解析器读取每一行并存储到字符串中以供进一步处理

String line = {"action": "tweet", 
               "id": 16606634614844517897, 
               "message": "woop #ruby", 
               "timestamp": 1487149445603, 
               "user": "hugopeixoto"};

在使用“json-simple-1.1.1.jar”解析上面的字符串时,我收到一个错误:-

java.lang.NumberFormatException: For input string: "16606634614844517897"

解析上述 JSON 字符串的代码:-

JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(line);
String name =(String) json.get("user");

我想打印上面 JSON 字符串中的“用户”名称。

显然,id 是 Long 格式,因此例外。

您能否建议我一个解决方法来消除上述异常。我尝试了所有组合,但没有成功。

【问题讨论】:

  • 为什么不将id 设为字符串?必须是数字吗?问题是该数字超出了Long 范围。你可以通过运行new BigInteger("16606634614844517897").subtract(new BigInteger(Long.toString(Long.MAX_VALUE))) 看到
  • 您确定该行引发了异常吗?
  • 谢谢@ErnestKiwele。您发布的链接帮助我解决了这个问题。我切换到Gson。由于 json-simple 1.1.1 的限制,出现了这个问题。

标签: java json


【解决方案1】:

很明显,id是Long格式

不,抱歉,Long 的最大值如下:

9223372036854775807 <-- has a length of 19

当你的时候

16606634614844517897 <- has a length of 20

我看到两个简单的解决方案来解决您的问题。

如果 id 仅用于唯一标识(这里可能就是这种情况),您应该改用 String 吗?

如果您需要使用 id 并比较其数值或对其执行数字运算,我对此表示怀疑,您仍然可以使用BigInteger,如下所示

new BigInteger("16606634614844517897");

【讨论】:

  • 感谢您的帮助。这个问题是由于 json-simple 1.1.1 的限制。我切换到 gson,我的问题得到了解决。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 2012-06-20
  • 2011-04-04
  • 1970-01-01
  • 2019-01-10
  • 2013-08-02
  • 2015-09-09
相关资源
最近更新 更多