Yevgeny Simkin
Yevgeny Simkin

Reputation: 28379

Why would different versions of Android re-order my JSON in different ways?

I have a bit of JSON (I made it out of clay) and when it's dry and ready with Android it will play... or not play - depending on the version.

I know that only JSON Array's order are guaranteed to be preserved. However, what I'm seeing is that in Lollipop (5.x) the children of a given object are read consistently in the order in which they are loaded from the JSON file BUT in KitKat (4.4.1) they appear in a different order but always in the SAME different order!!

in other words the file might be

"colors":{"red":"0xFF0000", "blue":"0x0000FF", "green":"0x00FF00"}

and in 5.x when I grab the keys() Iterator and cycle through them they arrive in the original order (red, blue, green) but in 4.4.x they arrive as green , red, blue. But they arrive in the SAME different order each time.

I'm really curious why the JSON parser would behave differently form one version of Android to the next.

Upvotes: 1

Views: 98

Answers (1)

Grishka
Grishka

Reputation: 2595

JSON objects, much like HashMaps, are key-value things, you're not supposed to rely on the order of the keys in the iterator, you're supposed to know the key in advance and then query a value that corresponds to it. If you need your objects in a specific order, I'd suggest using a JSON array like this:

"colors":[{"name":"red", "color":"0xFF0000"},{"name":"blue", "color":"0x0000FF"},...]

The different order is likely due to the JSON parser internally using some sort of HashMap and its implementation (either the hash map or the hashing algorithm for the keys) differs from version to version.

Upvotes: 2

Related Questions