Search code examples
vb.netserializationjson.netwebrequestjsonserializer

VB.NET converting Object to JSON


I am creating a web request of type POST but the converted JSON is not in the correct format. Below is my function:

Public Function CreateWebRequestPOST(ByVal strURL As String, objInput As Object) As JArray
        Try
            'Serialize the posted data & convert to bytes
            Dim inputJson = (New JavaScriptSerializer()).Serialize(objInput)
            Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson)

            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(strURL), HttpWebRequest)
            request.Method = "POST"
            request.ContentType = "application/json"
            request.Accept = "application/json"
            request.ContentLength = bytes.Length
            request.Expect = "application/json"
            request.GetRequestStream().Write(bytes, 0, bytes.Length)

            Dim username = "username"
            Dim password = "passoword"
            request.Credentials = New NetworkCredential(username, password)


            Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
                Dim reader As StreamReader
                Dim rawresp As String
                reader = New StreamReader(response.GetResponseStream())
                rawresp = reader.ReadToEnd()
                Dim array As JArray = JArray.Parse(rawresp)
                reader.Close()
                response.Close()
                Return array
            End Using
        Catch ex As Exception
            Dim empty As New JArray
            Return empty
        End Try
    End Function

The Object I am sending in the parameter is as follows:

Dim objReq As New RequestBodyList
Dim orderlist As New OrderList

orderlist.currency = "test"
orderlist.id = "test"
orderlist.amount = 100

objReq.apiOperation = "some_action"
objReq.order = orderlist


Dim response = main.CreateWebRequestPOST("some_URL", objReq)

Public Class RequestBodyList
    Public Property apiOperation() As String
    Public Property order() As New OrderList
End Class

Public Class OrderList
    Public Property currency() As String
    Public Property id() As String
    Public Property amount() As Integer
End Class

Below is a sample output for the inputJSON variable:

"{""apiOperation"":""Some_action"",""order"":{""currency"":""USD"",""id"":""test1234"",""amount"":100}}"

It looks like the converted JSON is not a correct format. What was done wrong here? What caused the double quotes to appear?

This is how the Request body should be sent:

Request body (JSON object)

{ 
    "apiOperation": "some_action", 
    "order": {
        "currency": "USD",
        "id": "some_order_id" ,
        "amount": 50
    } 
}

Solution

  • Public Function CreateWebRequestPOST(ByVal strURL As String, objInput As Object) As JObject
            Try
                'Serialize the posted data & convert to bytes
                Dim inputJson = (New JavaScriptSerializer()).Serialize(objInput)
                Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson)
    
                Dim request As HttpWebRequest = DirectCast(WebRequest.Create(strURL), HttpWebRequest)
                request.Method = "POST"
                request.ContentType = "application/json"
                request.Accept = "application/json"
                request.ContentLength = bytes.Length
                request.Expect = "application/json"
                request.GetRequestStream().Write(bytes, 0, bytes.Length)
    
                Dim username = "username"
                Dim password = "passoword"
                request.Credentials = New NetworkCredential(username, password)
    
    
                Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
                    Dim reader As StreamReader
                    Dim rawresp As String
                    reader = New StreamReader(response.GetResponseStream())
                    rawresp = reader.ReadToEnd()
                    Dim array As JObject = JObject.Parse(rawresp)
                    reader.Close()
                    response.Close()
                    Return array
                End Using
            Catch ex As Exception
    
            End Try
        End Function
    

    Ended up realizing that the return type should be of type Object and not Jarray.