Home:ALL Converter>Parse JSON uint32/uint64 numbers in Java

Parse JSON uint32/uint64 numbers in Java

Ask Time:2020-03-23T22:22:36         Author:Yiorgos

Json Formatter

I want to parse some JSON data in uint32 and uint64 format that are sent as numbers (without quotes), and then use them in java.

I found out that I can store them as unsigned integers via the parseUnsignedInt(String) method, but the problem is that I cannot get the json value as a string, because it's lacking quotes. If I parse it as an int, the value returned is wrong before I have the chance to convert it.

Example:

// data is a JSONObject containing: {"number" : 4294967294}
...
System.out.println(data.getInt("number"));
// returns: -10001
System.out.println(Integer.parseUnsignedInt(data.getString("number")));
// returns: JSONObject["number"] not a string.
System.out.println(Integer.parseUnsignedInt(Integer.toString(data.getInt("number"))));
// returns: Illegal leading minus sign on unsigned string -10001.

Is there a way to extract the value from the json object as a string (or any other way that doesn't ruin it)?

Author:Yiorgos,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60815401/parse-json-uint32-uint64-numbers-in-java
samabcde :

Suppose the library using is org.json. getLong method can not support uint64. We should use getBigInteger in such case.\n\nimport org.json.JSONObject;\n\npublic class JsonParseLargeInteger {\n public static void main(String[] args) {\n String uint32MaxValueJson = \"{\\\"number\\\" : 4294967296}\";\n JSONObject uint32MaxValueJsonObject = new JSONObject(uint32MaxValueJson);\n System.out.println(((Integer) uint32MaxValueJsonObject.getInt(\"number\")).toString());\n // Result is 0\n System.out.println(((Long) uint32MaxValueJsonObject.getLong(\"number\")).toString());\n // Result is 4294967296\n System.out.println(uint32MaxValueJsonObject.getBigInteger(\"number\").toString());\n // Result is 4294967296\n\n String uint64MaxValueJson = \"{\\\"number\\\" : 18446744073709551615}\";\n JSONObject uint64MaxValueJsonObject = new JSONObject(uint64MaxValueJson);\n System.out.println(((Integer) uint64MaxValueJsonObject.getInt(\"number\")).toString());\n // Result is -1\n System.out.println(((Long) uint64MaxValueJsonObject.getLong(\"number\")).toString());\n // Result is -1\n System.out.println(uint64MaxValueJsonObject.getBigInteger(\"number\").toString());\n // Result is 18446744073709551615\n }\n}\n",
2020-03-23T15:10:57
yy