将JSONObject解析为整数时int错误无效
基本上我想将JSONObject json转换为整数(127181078)。当我使用此代码:将JSONObject解析为整数时int错误无效
int intOfReceivedID = Integer.parseInt(json);
我收到此错误信息:
java.lang.NumberFormatException:无效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,但我得到了一些错误,当我分析文本为整数。
- 有人可以告诉我这里发生了什么吗?
- 你能帮我把我的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);
这个问题是混乱,但您的错误消息,看起来这是一个Java疑问,与JSON无关,因为在这种情况下,您的json字符串看起来好像不包含json(来自异常消息)。
它看起来像问题是你的JSON值是一个数字加上Integer.parseInt不处理的额外空间。
尝试
Integer.parseInt(json.trim())
int intOfReceivedID = Integer.parseInt(json);
我得到这个错误 消息:
java.lang.NumberFormatException:无效INT:127181078"
这种情况的原因有身份证号末尾的换行符不能是pa rsed到一个整数。
当我使用此代码:
char[] charArray = json.toCharArray(); String stringCharArray = charArray.toString(); testTextView.setText(stringCharArray);
testTextView给我:[C @ 2378e625
默认情况下,在对象上调用toString()
打印对象的存储位置(在这种情况[[email protected]
)。这就是TextView
中显示的内容。
然而,当我使用此代码:
preprocessedjson = String.valueOf(json); testTextView.setText(preprocessedjson);
TextView的给人127181078,但我得到了一些错误,当我分析 文本为整数。
将文本解析为整数时会出错,因为它在最后仍然有无效的换行符。
如果您从服务器收到只包含long的JSONObject
,则可以使用getLong()
或optLong()
方法检索整数值。 JSON解析器自动处理所有解析,并且不需要做任何额外的工作。
JSONObject json = jparser.makeHttpRequest("http://myurl.nl/readspecifictextfile.php","POST",data);
final long receivedId = json.optLong();
谢谢@ W.K.S。为了解释! –
也许你应该解释为什么你想要将一个对象转换为完全不同的不兼容类型?你确定你不想从一个特定的键的对象中检索一个int值吗? – Deadron
尝试解析它,而不是int –
@Deadron:你的评论给我的想法,我做了一些愚蠢的事情。我确实想要检索对象的int值,但我不理解评论的“特定关键”。感谢您的帮助! –