JSONArray(String json) returns "Infinite" when parsing some unquoted (invalid) JSON

StackOverflow https://stackoverflow.com/questions/23680832

  •  23-07-2023
  •  | 
  •  

Вопрос

A curiosity:

JSONArray rfidArray1 = new JSONArray("[047c04fae63684]");

returns a JSONArray whose first value is a Double with value of Infinity, whereas:

JSONArray rfidArray1 = new JSONArray("[04b2b6f2443680]");

returns a JSONArray whose first value is a String with value of 04b2b6f2443680.

This is clearly invalid JSON which should throw a JSONException, but instead it sporadically returns broken values. It seems to be lenient with some values and return a "proper" JSONArray, but with some others it does not. Here are some more values:

Returns first value of Double with value of Infinity:

"[047c04fae63684]"
"[042579FAE63680]"
"[048C22FAE63684]"
"[049360FAE63680]"

Returns first value of String with 'proper' value:

"[04bb97d27c3680]"
"[04BB97D27C3680]"
"[04337FF2443681]"
"[04b2b6f2443680]"
"[0447E3FAE63680]"
"[\"047c04fae63684\"]"
"[\"049360FAE63680\"]"

I'm using Android 4.4.2 API level 19.

Это было полезно?

Решение

Your 'double' values contain the letter E, which is valid double syntax IF the parser recognized hexadecimal, which JSONArray probably does. E means in the floating point world as times 10 to the power of

numbers1[E/e]numbers2 is parsed as:

numbers1 * (10 ^ numbers2), or

numbers1 times 10 to the power of numbers2

Where numbers[1/2] represent any combination of hexadecimal digits. Sooo....

047c04fae63684 is the same as

047c04fa * (10 ^ 64684) and double does not have enough data space to hold that exponent, so it overflows and returns Infinity.

Meanwhile the JSONArray parser has no clue what to with "[04b2b6f2443680]", so im geussing it assumes that because it contains non digits, that it must be a string and it returns it as a String.

For "[\"049360FAE63680\"]" you enclosed the array value in quotes so the parser automatically sees them and says 'Hey, thats a string, lets just return that' and doesn't do anything else.

Sorry if the data is inaccurate, I have a bad head cold.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top