android - 为什么 org.json.JSONObject getLong 和 getString 不相等

标签 android json org.json

代码如下:

     JSONObject contentObject = new JSONObject(content);
     JSONObject params = contentObject.getJSONObject("response_params");
     Log.d("onTest", "channel_id:" + params.getString("channel_id"));
     Log.d("onTest", "channel_id:" + params.getLong("channel_id"));

日志打印:

   08-21 12:46:21.470: DEBUG/onTest(25228): onMessage: content : {"response_params":{"appid":"1071410","channel_id":"3537275240990320342","user_id":"714893193627619861"},"request_id":1293438498}
   08-21 12:46:21.480: DEBUG/onTest(25228): channel_id:3537275240990320342
   08-21 12:46:21.480: DEBUG/onTest(25228): channel_id:3537275240990320128

为什么 getLong 的值为 3537275240990320128,而 String 的值为 3537275240990320342?

最佳答案

根据文档 here ,

public long getLong (String name)

Returns the value mapped by name if it exists and is a long or can be coerced to a long. Note that JSON represents numbers as doubles, so this is lossy; use strings to transfer numbers via JSON.

编辑: 要亲自查看,您可以这样做

JSONObject json = new JSONObject();
try {
    json.put("test", "3537275240990320342");
    String str = json.getString("test");
    double dou = Double.parseDouble(str);
    long lo = (long) dou;
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

您会看到 lo 的值正是您执行 getLong 时得到的值

关于android - 为什么 org.json.JSONObject getLong 和 getString 不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18349131/

相关文章:

java - 如何在ubuntu中使用eclipse luna配置android SDK?

java - 更改现有应用程序的 admob id

java - 我可以从 JSONObject 中获取值(value)而无需提及其名称吗?

android - 如何将 RevMob 与 LibGdx 集成

php - Android Asynctask更新查询远程mysql服务器

Android Studio Gradle 错误

json - 如何在 Angular 中基于外部 NgFor 建立内部 NgFor

c# - 将 JSON 字符串反序列化为 C# 复杂类对象

unicode - 如何在 freemarker 模板处理中转义 unicode 符号?

java - 使用 org.json 库格式化 LocalDateTime 时出现问题