Android Question How to create nested arrays with json

Alexander Stolte

Expert
Licensed User
Longtime User
Hey,

how can i create this with the JSONGenerator?
B4X:
{
  "name":"John",
  "age":30,
  "cars": [
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
  ]
}

if i put a json string into the JSONParser, then is this my result:
B4X:
{
   "DocumentCode":"007",
   "DocumentTitle":"Doc Title",
   "AttchmentData":"{\"AttchmentName\":\"Rücksendezentrum.pdf\",\"AttachmentTitle\":\"This is the title\",\"AttachmentData\":\"test\"}"
}
 

DonManfred

Expert
Licensed User
Longtime User
how can i create this with the JSONGenerator?
Create a Map wth a similar content and Structure.
Initialize the parser with this Map and output the generated String.

Edit:

B4X:
    Dim json As Map
    json.Initialize
    json.Put("name","John")
    json.Put("age",30)
    '
    ' Cars needs a list first
    Dim cars As List
    cars.Initialize
    
    Dim ford As Map
    ford.Initialize
    ford.Put("name","Ford")
    Dim models As List
    models.Initialize
    models.AddAll(Array As String("Fiesta", "Focus","Mustang"))
    ford.Put("models",models)
    cars.Add(ford)

    Dim bmw As Map
    bmw.Initialize
    bmw.Put("name","BMW")
    Dim models As List
    models.Initialize
    models.AddAll(Array As String("320", "X3","X5"))
    bmw.Put("models",models)
    cars.Add(bmw)

    Dim fiat As Map
    fiat.Initialize
    fiat.Put("name","Fiat")
    Dim models As List
    models.Initialize
    models.AddAll(Array As String("500", "Panda"))
    bmw.Put("models",models)
    cars.Add(fiat)

    json.Put("cars",cars)
        
    Dim jgen As JSONGenerator
    jgen.Initialize(json)
    Log(jgen.ToPrettyString(2))   
    Log(jgen.ToString)
 
Last edited:
Upvote 0

Jorge M A

Well-Known Member
Licensed User
Longtime User
My two cents for the same:
B4X:
Sub DoJson
    Private root As Map
    Private cars As List
    Private name As String
    Private models As List
    
    Private JS As String
    root.Initialize
    cars.Initialize
    
    root.Put("name", "John")
    root.Put("age", 30)
    
    name="Ford"
    models.Initialize2(Array As String("Fiesta","Focus","Mustang"))
    cars.Add(CreateMap("name":name,"models":models))
 
    name="BMW"
    models.Initialize2(Array As String("320","X3","X5"))
    cars.Add(CreateMap("name":name,"models":models))
    
    name="Fiat"
    models.Initialize2(Array As String("500","Panda"))
    cars.Add(CreateMap("name":name,"models":models))
    'Add
    root.Put("cars",cars)
        
    Private JSONGenerator As JSONGenerator
  
    JSONGenerator.Initialize(root)

    JS = JSONGenerator.ToPrettyString(2)
    Log(JS)
  
End Sub
 
Upvote 0
Top