来自jsonobject的错误值 - java

时间:2013-03-05 20:40:11

标签: java hashtable

这是我上一个问题的延续: how to keep data stored into a hashtable - java

这是json:

{"DeviceID":"35181805087546548","TotalCount":"0","Timestamp":"2013-03-05 14:30:15"}

以下是我的哈希表的声明:

    private static Hashtable<Integer,String> table = new Hashtable<Integer,String>();
    private static AtomicInteger count = new AtomicInteger() ;

以下是解析jsonobject的代码:

        JSONObject jsonObj;
        try {
            jsonObj = new JSONObject(string);
            int id = jsonObj.optInt("DeviceID", count.addAndGet(1) );
            String name = jsonObj.toString();
            table.put(id, name);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

使用下面的代码,即使json中的“DeviceID”发生变化,我的ID始终为“2147483647”。 任何提示?

非常感谢

3 个答案:

答案 0 :(得分:4)

你的值对于int来说太大了。最大允许值为2,147,483,647。见What is the maximum value for an int32?。您需要将值解析为long。

答案 1 :(得分:1)

Java中的maximum value of an integer为2,147,483,647,因此您的设备ID不适合。您可能需要将其存储为long(最大值9,223,372,036,854,775,807)。

答案 2 :(得分:1)

您获得的数字是有符号整数的最大值,您需要使用long,否则您的结果将限制为Integer.MAX_VALUE。