B4J Question JSONGenerator map instead of list, not the ouput I want

TorontoJim

Member
Licensed User
Longtime User
I am trying to create a JSON file using the JSONGenerator.

This is the output I desire:

B4X:
{
    [
        {
            "Text": "Item #1"
        },
        {
            "Text": "Item #2"
        },
    ]
}

However, the JSONGenerator requires that you pass it a map, not a list. This means I have to set a key. I tried passing NULL and then an empty string and got the expected results:

B4X:
{
    "null": [
        {
            "Text": "Item #1"
        },
        {
            "Text": "Item #2"
        },
    ]
}

OR

{
    "": [
        {
            "Text": "Item #1"
        },
        {
            "Text": "Item #2"
        },
    ]
}

So the question is, how do I get the structure:

B4X:
{[  ...nifty JSON stuff...   ]}

...without the maps one and only key showing up?
 

TorontoJim

Member
Licensed User
Longtime User
I realized I can use Substring2 to get what I want, but I'd like to know if there is a way that is correct to do the above, without resorting to substrings?

B4X:
Dim listItems As List
listItems.Initialize
listItems.Add(CreateMap("Text" : "Item #1"))
listItems.Add(CreateMap("Text" : "Item #2"))

Dim mapJSON As Map
mapJSON.Initialize
mapJSON.Put(Null, listItems)

Dim json As JSONGenerator
json.Initialize(mapJSON)

Dim strJson As String = json.ToString
strJson = strJson.SubString2(8, strJson.Length - 1)
Log(strJson)

Output: [{"Text":"Item #1"},{"Text":"Item #2"}]
 
Upvote 0
Top