B4J Question Retrieve Json Map in correct order of insertion?

MathiasM

Active Member
Licensed User
Hello

Is there a way to get a Json Map in the order it was put into. It's not really an issue, but for API browsers and documentation it's nicer to return Json results (and errors following RFC 7807) in the order people expect.

Consider this code:
B4X:
Dim m As Map
   m.Initialize
   m.Put("first", "testvalue")
   m.Put("last", "testvalue")
 
    Dim j As JSONGenerator
    j.Initialize(m)
    Log(j.ToPrettyString(4))

Will return this:

{
"last": "testvalue",
"first": "testvalue"
}

I could write a reverse function, but maybe an 'Add' function on a Map instead of 'Put' would be more graceful?

Thanks
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
I could write a reverse function
It will not help. The order is based on the strings hash code.

While B4J Map preserves the order of items, the underlying map created by the JSON SDK doesn't preserve the order. There is no simple way to make it preserve the order (without sacrificing performance).
 
Upvote 0

MathiasM

Active Member
Licensed User
Thanks for that link FrostCodes! Didn't notice that thread!
Altough I seem to be doing something wrong, as it doesn't work for me. See that thread for more details.
 
Upvote 0
Top