Home > Software design >  Json with parameters in Vb.net
Json with parameters in Vb.net

Time:02-23

I need to send json data to an API including a QR code and some other values.

this is what i got from them

The needed parameter is:

• Parameter "data" in JSON: id -> 100 (fixed, it is the ID needed for our software) qrcode -> QRcode value

Example: data={"id":"100","qrcode":"VL11bbdb186a3a6dcfc57a1b07149c9a0e"}

and this is the code i use

Call:

     Dim jsonPost As New JsonPost(postadress)
                Dim dictqr As New Dictionary(Of String, Object)
                dictqr.Add("id", lastmeas.id)
                dictqr.Add("qrcode", lastmeas.qrcode)
                jsonPost.PostData(dictqr)

and this is the definition

    Public Class JsonPost

        Private urlToPost As String = ""

        Public Sub New(ByVal urlToPost As String)
            Me.urlToPost = urlToPost
        End Sub

        Public Function PostData(ByVal dictData As Dictionary(Of String, Object)) As Boolean
            Dim webClient As New WebClient()
            Dim resByte As Byte()
            Dim resString As String
            Dim reqString() As Byte

            ServicePointManager.ServerCertificateValidationCallback = Function(o, certificate, chain, errors) True
            Try
                webClient.Headers("content-type") = "application/json"
                webClient.Headers("accept") = "*/*"
                reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dictData, Newtonsoft.Json.Formatting.None))
                resByte = webClient.UploadData(Me.urlToPost, "POST", reqString)
                resString = Encoding.Default.GetString(resByte)
                Form1.respuesta_envio = resString
                webClient.Dispose()
                Return True
            Catch ex As Exception
                Form1.respuesta_envio = ex.Message
                CreateObject("WScript.Shell").Popup(ex.Message, 5, "Data not transfered")
            End Try
            Return False

        End Function

    End Class

if i deserialize, i get

{"id":"100","qrcode":"example"}

but i do not know how to include this data= part

CodePudding user response:

The API appears to be asking you to send a JSON string inside a form-url-encoded parameter. That's unpleasant and not a logical way to design an API, but if that's what they require then that's what you'll have to do.

Therefore you need to:

  • remove the Content-Type header telling the server to expect a JSON body in the request. What you'll actually be sending is form-url-encoded data where the one parameter happens to contain JSON within its value. i.e. remove this line:
webClient.Headers("content-type") = "application/json"
  • prepend the data= bit to the JSON string generated by the SerializeObject function:
reqString = Encoding.Default.GetBytes("data=" & JsonConvert.SerializeObject(dictData, Newtonsoft.Json.Formatting.None))
  • Related