JSON – JavaScript Object Notation, is a popular text format and for a good reason. It is human readable, simple, compact, relatively fast to parse and nicely mapped to Lists and Maps.
Example of a JSON string:
{ "Version": 1, "Items": [ { "Count": 10, "Name": "Item #1" }, { "Count": 2, "Name": "Item #2" }, { "Count": 43, "Name": "Item #3" } ], "ID": "abcdef" }
Elements inside curly brackets { … } are mapped to Map collections and elements inside square brackets [ … ] are mapped to List collections.
The above string is created with this code:
Dim Data As Map = CreateMap("Version": 1.00, "ID": "abcdef", _
"Items": Array( _
CreateMap("Name": "Item #1", "Count": 10), _
CreateMap("Name": "Item #2", "Count": 2), _
CreateMap("Name": "Item #3", "Count": 43)))
Dim jg As JSONGenerator
jg.Initialize(Data)
Dim JsonString As String = jg.ToPrettyString(4)
Log(JsonString)
Parsing this string is simple:
Dim parser As JSONParser
parser.Initialize(JsonString)
Data = parser.NextObject
Dim Items As List = Data.Get("Items")
For Each m As Map In Items
Log(m.Get("Name") & ": " & m.Get("Count"))
Next
In B4X you can parse and generate JSON strings with the Json library. In B4R, where the memory is very limited, it requires a bit more work: https://www.b4x.com/android/forum/threads/107410
There is an online B4J tool that can help with parsing JSON strings: https://b4x.com:51041/json/index.html
Don’t rely on the order of elements in the map collections. If the order needs to be preserved then use a list, it can be a list of maps.
Don’t try to generate JSON strings without JsonGenerator. Some of the characters need to be escaped and you will just waste your precious time.