B4J Question How to read json post

Pablo Torres

Active Member
Licensed User
Longtime User
Hi everyone, sorry to disturb, have been searching for days about this but havent found anything.

If I have a jserver running in (example) "https://myserverapi.com" and I send a poststring to "https://myserverapi.com?method=getcards" with the following post: {"idevento":5,"filter":"NO"}... I understand that with req.GetParameter("methhod") I obtain the value "getcards"... but how do I obtain the values 5 and "NO"?

I'm pretty sure it is a silly question, but would be great to have it answered


Many thanks
 

jahswant

Well-Known Member
Licensed User
Longtime User
B4X:
 if req.Method.ToUpperCase = "POST" Then
         Dim data() As Byte = Bit.InputStreamToBytes(req.InputStream)
        Log(BytesToString(data, 0, data.Length, "UTF-8"))
    End If

 
Upvote 1

aeric

Expert
Licensed User
Longtime User
Similar to @jahswant 's answer, I have a function in my WebApiUtils which read the posted JSON data string into B4X Map.

B4X:
Public Sub RequestData (Request As ServletRequest) As Map
    Dim data As Map
    Dim inp As InputStream = Request.InputStream
    If inp.BytesAvailable <= 0 Then
        Return data
    End If
    Dim buffer() As Byte = Bit.InputStreamToBytes(inp)
    Dim str As String = BytesToString(buffer, 0, buffer.Length, "UTF-8")
    data = str.As(JSON).ToMap
    Return data
End Sub
 
Upvote 0

aeric

Expert
Licensed User
Longtime User
Take note if you also want to read the parameter "method=getcards"

Tip about POST requests: if you want to get a URL parameter (req.GetParameter) then do it only after reading the payload, otherwise the payload will be searched for the parameter and will be lost.
 
Upvote 0

Pablo Torres

Active Member
Licensed User
Longtime User
That works! Many Thanks
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…