【问题标题】:Error invalid int when parsing JSONObject into an integer将 JSONObject 解析为整数时出现无效 int 错误
【发布时间】:2018-02-10 21:26:21
【问题描述】:

基本上我想将 JSONObject json 转换为整数 (127181078)。当我使用此代码时:

int intOfReceivedID = Integer.parseInt(json);

我收到此错误消息:

java.lang.NumberFormatException: Invalid int: 127181078"

当我使用这段代码时:

char[] charArray = json.toCharArray();
String stringCharArray = charArray.toString();
testTextView.setText(stringCharArray);

testTextView 给我:[C@2378e625

但是,当我使用此代码时:

preprocessedjson = String.valueOf(json);
testTextView.setText(preprocessedjson);

TextView 给出 127181078,但是当我将文本解析为整数时出现一些错误。

  1. 谁能告诉我这里发生了什么?
  2. 您能帮我将 JSONObject 转换为整数吗?

这是php代码:

$myfile = fopen($filename, 'r') or die("Unable to open file!");
echo fread($myfile,filesize($filename));
fclose($myfile);

这是makeHttpRequest:

JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);

【问题讨论】:

  • 也许您应该解释一下为什么要将 Object 转换为完全不同的不兼容类型?您确定不想从对象的特定键处检索 int 值吗?
  • 尝试将其解析为 long 而不是 int
  • @Deadron:你的评论让我觉得我在做一些愚蠢的事情。我确实想检索对象的 int 值,但我不明白您评论的“特定键”。感谢您的帮助!
  • @Navneet Krishna:我也试过了,但是我得到了同样的错误。我选择整数的长度始终在位限制内。
  • 您应该发布解析原始 JSON 字符串的代码。如果您使用的是 JSON 解析器(如果不是,则应该使用),从对象中检索值通常很简单。听起来您可能正在手动解析值并弄乱值检索。

标签: android json integer


【解决方案1】:

这个问题令人困惑,但从您的错误消息看来,这是一个与 JSON 无关的 Java 问题,因为在这种情况下,您的 json String 看起来实际上并不包含 json(来自异常消息)。

看起来问题是您的 json 值是一个数字加上 Integer.parseInt 无法处理的额外空格。

试试

Integer.parseInt(json.trim())

【讨论】:

    【解决方案2】:
    int intOfReceivedID = Integer.parseInt(json); 
    

    我收到此错误 留言:

    java.lang.NumberFormatException: 无效 int: 127181078"

    这是因为 ID 末尾有一个换行符,无法解析为整数。

    当我使用这段代码时:

    char[] charArray = json.toCharArray();
    String stringCharArray = charArray.toString();
    testTextView.setText(stringCharArray);
    

    testTextView 给我:[C@2378e625

    默认情况下,对对象调用toString() 会打印对象的内存位置(在本例中为[C@2378e625)。这就是TextView 中显示的内容。

    但是,当我使用此代码时:

    preprocessedjson = String.valueOf(json);
    testTextView.setText(preprocessedjson);
    

    TextView 给出 127181078,但解析时出现一些错误 将文本转换为整数。

    将文本解析为整数时会出错,因为它的末尾仍有无效的换行符。

    如果您从服务器接收到的JSONObject 只包含一个长整数,那么您可以使用getLong()optLong() 方法来检索整数值。 JSON 解析器会自动处理所有解析,您无需做任何额外的工作。

    JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
    final long receivedId = json.optLong();
    

    【讨论】:

    • 谢谢@W.K.S.求解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    相关资源
    最近更新 更多