【发布时间】: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 的限制,出现了这个问题。