如何自定义VB中的格式HTTP JSON POST请求

时间:2018-04-24 20:35:58

标签: vb.net linq post json.net

这是最终结果{“recordType”:“b”,“recordNumber”:1550316,“pickupLocation”:“de”}

Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
    'GridView1.EditIndex = e.NewEditIndex
    If e.CommandName = "Hold" Then
        'Determine the RowIndex of the Row whose Button was clicked.
        Dim rowIndex As Integer = Convert.ToInt32(e.CommandArgument)

        'Reference the GridView Row.
        Dim row As GridViewRow = GridView1.Rows(rowIndex)

        'Fetch values.
        Dim recordId As String = TryCast(row.FindControl("lblRecordId"), Label).Text
        Dim recordType As String = TryCast(row.FindControl("lblrecordType"), Label).Text
        Dim homeCode As String = TryCast(row.FindControl("lblHomeCode"), Label).Text
      Dim input As Object = New With {
           .recordType =  recordType ,
           .recordNumber = recordId,
           .pickupLocation =  homeCode 
    }


      Dim inputJson As String = JsonConvert.SerializeObject(input)
      Dim request3 As HttpWebRequest
      Dim response3 As HttpWebResponse = Nothing

      request3 = DirectCast(WebRequest.Create("SOMEURL"), HttpWebRequest)
            request3.Headers.Add("Authorization", "Bearer " + accessToken)
            request3.Accept = "application/json"
            request3.ContentType = "application/json"
            request3.Method = "POST"

      Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson)



     Using stream As Stream = request3.GetRequestStream()
                stream.Write(bytes, 0, bytes.Length)
                stream.Flush()
                stream.Close()
          End Using
      Using httpResponse As HttpWebResponse = 
      DirectCast(request3.GetResponse(), HttpWebResponse)
                Using stream As Stream = httpResponse.GetResponseStream()
                    'lblOutput.Text = (New StreamReader(stream)).ReadToEnd()
                End Using
            End Using
         End If
      End Sub

InputJson =“{”“recordType”“:”“b”“,”“recordNumber”“:”“1550316”“,”“pickupLocation”“:”“de”“}”

返回=“httpStatus”:400,   “name”:“无效的JSON”,   “description”:“JSON对象缺少字段或字段包含无效数据”

我需要帮助正确格式化我的帖子请求,如下所示请注意记录号值没有引号.->

{"recordType": "b", "recordNumber": 1550316, "pickupLocation": "de"}

TY:)

1 个答案:

答案 0 :(得分:0)

我的猜测是recordId是一个字符串类型。

选项1:创建一个具体的类并远离匿名类型。

Public Class YourClass
    Public Property recordType As String
    Public Property recordNumber As Integer
    Public Property pickupLocation As String
End Class

选项2:如果您 SURE 这是一个整数,那么只需在初始化匿名类型时将其转换为此类。

    Dim input As Object = New With {
                .recordType = "b",
                .recordNumber = System.Convert.ToInt32(recordId),
                .pickupLocation = "de"
    }