Android Question Question about dynamic JSON

Antisociale

New Member
Hello everybody! I'm working through an example with JSON, I have the following question? How can implement a dynamic number of elements?

{
"Version": 1,
"Items": [
{
"Count": 10,
"Name": "Item #1"
},
{
"Count": 2,
"Name": "Item #2"
},
{
"Count": 43,
"Name": "Item #3"
}
],
"ID": "abcdef"
}
B4X:
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)

In this example, the number of elements in the "ITEMS" group is 3. Unfortunately, I can’t figure out how to make the number of elements not predetermined. Please excuse my English.
 

aeric

Expert
Licensed User
Longtime User
Use List instead.

B4X:
Dim Items As List
Items.Initialize
Items.Add(CreateMap("Name": "Item #1", "Count": 10))
Items.Add(CreateMap("Name": "Item #2", "Count": 2))
Items.Add(CreateMap("Name": "Item #3", "Count": 43))
Items.Add(CreateMap("Name": "Item #4", "Count": 9))

Dim Data As Map = CreateMap("Version": 1.00, "ID": "abcdef", _
"Items": Items)
Dim jg As JSONGenerator
jg.Initialize(Data)
Dim JsonString As String = jg.ToPrettyString(4)
Log(JsonString)
 
Upvote 0

Antisociale

New Member
Use List instead.

B4X:
Dim Items As List
Items.Initialize
Items.Add(CreateMap("Name": "Item #1", "Count": 10))
Items.Add(CreateMap("Name": "Item #2", "Count": 2))
Items.Add(CreateMap("Name": "Item #3", "Count": 43))
Items.Add(CreateMap("Name": "Item #4", "Count": 9))

Dim Data As Map = CreateMap("Version": 1.00, "ID": "abcdef", _
"Items": Items)
Dim jg As JSONGenerator
jg.Initialize(Data)
Dim JsonString As String = jg.ToPrettyString(4)
Log(JsonString)
Thank you very much!
 
Upvote 0

PaulMeuris

Well-Known Member
Licensed User
You could also write it like this:
B4X:
    Dim Items As List
    Items.Initialize
    Dim names As Map = CreateMap("first":10,"second":2,"third":43,"fourth":9)
    For Each key As String In names.Keys
        Dim itemmap As Map = create_item(key,names.Get(key))
        Items.Add(itemmap)
    Next
    Dim data As Map = CreateMap("Version": 1.00, "ID": "abcdef", "Items": Items)
    Log(data.As(JSON).ToString)

Private Sub create_item(name As String,cnt As Int) As Map
    Return CreateMap("Name": name, "Count": cnt)
End Sub
The input information comes from the names map.
The output information is stored in the data map.
The type conversion .As(JSON) can be used to convert the map to a JSON string that can be written to a file using the file.writestring() method.
 
Upvote 0
Top