Android Question Generating JSON and MAP Problems

roycegerikchua

Member
Licensed User
Longtime User
B4X:
    Map1.Clear
    For xx = 0 To 10' Contactz.Size-1
        
        Map1.Put("name",xx)
        Map1.Put("mobile",xx)
        Data.InsertAt(xx,Map1)
        
        JSONGenerator.Initialize2(Data)
        Log (JSONGenerator.ToPrettyString(1))
    Next
'

here is the output

JSON:
[
 {
  "name": 0,
  "mobile": 0
 }
]

2nd run
JSON:
[
 {
  "name": 1,
  "mobile": 1
 },
 {
  "name": 1,
  "mobile": 1
 }
]

3rd run
JSON:
[
[
 {
  "name": 2,
  "mobile": 2
 },
 {
  "name": 2,
  "mobile": 2
 },
 {
  "name": 2,
  "mobile": 2
 }
]

however the final output should be

JSON:
[
 {
  "name": 0,
  "mobile": 0
 },
 {
  "name": 1,
  "mobile": 1
 },
 {
  "name": 2,
  "mobile": 2
 }
]

hope you guys can help i've been hammering my brains for a while now
 

Mahares

Expert
Licensed User
Longtime User
hope you guys can help i've been hammering my brains for a while now

B4X:
Dim data As List
    data.Initialize   
    For xx = 0 To 10' Contactz.Size-1
        Dim map1 As Map
        map1.Initialize
        map1.Put("name",xx)
        map1.Put("mobile",xx)
        data.InsertAt(xx,map1)
    Next
   JSONGenerator.Initialize2(data)
    Log (JSONGenerator.ToPrettyString(1))
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
You are using the same Map Each time. Try:

B4X:
    Map1.Clear
    For xx = 0 To 10' Contactz.Size-1
        Dim Map1 As Map
        Map1.initialize
        Map1.Put("name",xx)
        Map1.Put("mobile",xx)
        Data.InsertAt(xx,Map1) 
    Next
   JSONGenerator.Initialize2(Data)
   Log (JSONGenerator.ToPrettyString(1))

I was too slow again :)
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
B4X:
    Dim Data As List
    Data.Initialize

    For i = 0 To 10
        Data.Add(CreateMap("name": i, "mobile": i))
    Next

    Dim JSONGenerator As JSONGenerator
    JSONGenerator.Initialize2(Data)
    Log (JSONGenerator.ToPrettyString(4))

JSON:
[
    {
        "name": 0,
        "mobile": 0
    },
    {
        "name": 1,
        "mobile": 1
    },
    {
        "name": 2,
        "mobile": 2
    },
    {
        "name": 3,
        "mobile": 3
    },
    {
        "name": 4,
        "mobile": 4
    },
    {
        "name": 5,
        "mobile": 5
    },
    {
        "name": 6,
        "mobile": 6
    },
    {
        "name": 7,
        "mobile": 7
    },
    {
        "name": 8,
        "mobile": 8
    },
    {
        "name": 9,
        "mobile": 9
    },
    {
        "name": 10,
        "mobile": 10
    }
]

B4X:
Dim parser As JSONParser
parser.Initialize(<text>)
Dim root As List = parser.NextArray
For Each colroot As Map In root
    Dim name As Int = colroot.Get("name")
    Dim mobile As Int = colroot.Get("mobile")
Next
 
Last edited:
Upvote 0
Top