解析包含Long值的JSON String时的NumberFormatException

时间:2018-05-26 14:11:47

标签: java json

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

OnPropertyChanged("CalculatedPropertyName")

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

public int Quantity
{
    get { return quantity; }
    set 
    {
        if (value != quantity)
        {
            quantity = value;
            OnPropertyChanged();
            Result = Quantity * Price;
        }
    }
}

public int Price
{
    get { return price; }
    set 
    {
        if (value != price)
        {
            price = value;
            OnPropertyChanged();
            Result = Quanity * Price;
        }
    }
}

public int Result
{
    get { return result; }
    private set 
    {
        if (value != result)
        {
            result = value;
            OnPropertyChanged();
        }
    }
}

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

{"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字符串中的“user”名称。

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

您能否建议我解决上述异常问题。我尝试了所有组合,但没有奏效。

1 个答案:

答案 0 :(得分:2)

  

显然,id是Long格式

不,抱歉最大Long值如下:

9223372036854775807 <-- has a length of 19

而你的

16606634614844517897 <- has a length of 20

我看到了两个解决问题的简单方法。

如果id仅用于唯一标识的目的(这可能就是这种情况),那么您应该使用String代替?

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

new BigInteger("16606634614844517897");