Android Question I can't use JSONParser correctly

ema01

Active Member
Licensed User
Longtime User
Hello,
i'm receiving a json string;
B4X:
{"data":[{"id":"my-id","name":"my-name","status":"ACTIVE","createdAt":"some-time","updatedAt":"some-time"}],"meta":{"page":1,"limit":20,"total":1,"totalPages":1}}

prettified:
B4X:
{
  "data":[
    {
      "id":"my-id",
      "name":"my-name",
      "status":"ACTIVE",
      "createdAt":"some-time",
      "updatedAt":"some-time"
    }
  ],
  "meta":{
    "page":1,
    "limit":20,
    "total":1,
    "totalPages":1
  }
}

I'm interested in the "data" field, which contains and array of objects. However i've resorted to parsing the data manually.
I initialized a JsonParser on the raw string, and read a map using NextObject.

Now i get a map that has a single "data" key, and the content of "data" as a value. However, the string is not Json Anymore.
This is what i get:
B4X:
[{id=my-id, name=my-name, status=ACTIVE, createdAt=some-time, updatedAt=some-time}]
and that can't be read with JsonParser anymore.
As i said, i've already written a parser function, but i want to see what i'm doing wrong.

Thanks for helping
 

aeric

Expert
Licensed User
Longtime User
You mean you write your own Json Parser function?
Why you want to do that? B4X has Json library you can use.
It is also very easy to cast the child items as Map or List straight away.

B4X:
Private Sub TestJsonParser
    Dim s As String = $"{"data":[{"id":"my-id","name":"my-name","status":"ACTIVE","createdAt":"some-time","updatedAt":"some-time"}],"meta":{"page":1,"limit":20,"total":1,"totalPages":1}}"$
    Dim m As Map = s.As(JSON).ToMap
    For Each k As String In m.Keys
        Log(k)
    Next
    Log(" ")
    Dim data As List = m.Get("data")
    For Each m2 As Map In data
        For Each k2 As String In m2.Keys
            Log($"${k2} -> ${m2.Get(k2)}"$)
        Next
    Next
End Sub

Output:
Bash:
data
meta
 
id -> my-id
name -> my-name
status -> ACTIVE
createdAt -> some-time
updatedAt -> some-time
 
Upvote 1

aeric

Expert
Licensed User
Longtime User
that can't be read with JsonParser anymore.

Let say you assigned the value as String, you can still parse it but use parser.NextArray instead of parser.NextObject

B4X:
Dim data As String = m.Get("data")
Dim parser As JSONParser
parser.Initialize(data)
Dim list1 As List = parser.NextArray
Log(list1)
Dim map1 As Map = list1.Get(0)
Log(map1)

Output:
Bash:
(ArrayList) [{id=my-id, name=my-name, status=ACTIVE, createdAt=some-time, updatedAt=some-time}]
(MyMap) {id=my-id, name=my-name, status=ACTIVE, createdAt=some-time, updatedAt=some-time}
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
Nor that every JSON Object was then interpreted as a Map
No. If it starts with a { it is a MAP. If it starts with a [ it is a LIST.
 
Upvote 0
Top