Android Tutorial Convert collections to json and vice versa

The JSON libraries, which are internal libraries, were updated. The new version is 1.20.

There is a new JSON type which is used to convert maps or lists to json strings and vice versa, using the new As keyword.
The idea is that you have a collection or string, you direct the compiler to treat it as "JSON" and then convert it to a string or a collection.

It looks like this:
B4X:
Dim m As Map = CreateMap("asdasd": Array(1, 2, 3, 4))

Dim s As String = m.As(JSON).ToString
'equivalent to:
Dim jg As JsonGenerator
jg.Initialize(m)
Dim s As String = jg.ToPrettyString(4)

'and the other direction:
Dim s As String =  $"{"aaa": "bbb"}"$

Dim m As Map = s.As(JSON).ToMap 'ignore
'equivalent to:
Dim jp As JsonParser
jp.Initialize(s)
Dim m As Map = jp.NextObject
It also works with Lists.
 
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
You could also do this to switch from string to map
B4X:
    Dim m As Map = $"{"aaa": "bbb"}"$.As(JSON).ToMap 'ignore
    Log(m)

Unfortunately, the vice versa does not work, from map to string
B4X:
Dim s As String = CreateMap("asdasd": Array(1, 2, 3, 4)).As(JSON).ToString
 

Star-Dust

Expert
Licensed User
Longtime User
maybe it could work like that. So as to put everything on one line

B4X:
Dim s As String = MMap(CreateMap("asdasd": Array(1, 2, 3, 4))).As(JSON).ToString

B4X:
Private Sub MMap(M As Map) As Map
   Return M
End Sub
 
Last edited:

Nestor Castro Jr

Member
Licensed User
Hello Erel,

I think the iOS version you made available is still at 1.01 instead of 1.20 as indicated in the editor
Print 1.png
Print 2.png
 
Top