VB.NET 将对象转换为 JSON

VB.NET converting Object to JSON

我正在创建类型为 POST 的 Web 请求,但转换后的 JSON 格式不正确。以下是我的功能:

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

我在参数中发送的对象如下:

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

下面是 inputJSON 变量的示例输出:

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

看起来转换后的 JSON 格式不正确。 这里做错了什么? 出现双引号的原因是什么?

请求正文应该这样发送:

请求正文(JSON对象)

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

无法发表评论,所以必须将其作为答案!你能提供更多细节吗?当你说...

Below is a sample output for the inputJSON variable:

你能确认你认为格式有什么问题吗,以我有限的经验,它看起来还可以。

下面是我的一个项目中的代码片段,以及我如何将 JSON 输出处理到流 reader 然后使用 JsonConvert.DeserializeObject,有点迂回但它剂量工作,它最终变得更具可读性。

希望对您有所帮助, R

Function test()

    Try

        'Get obligations
        Dim origResponse As HttpWebResponse
        Dim AccessToken As String = Access_Token
        Dim origRequest As HttpWebRequest = Nothing

        origRequest = DirectCast(HttpWebRequest.Create("https://api.service.hmrc.gov.uk/organisations/vat/" + CoVRN + "/obligations?from=2019-01-01&to=" + Now.ToString("yyyy-MM-dd") + "&status=O"), HttpWebRequest) 'for testing

        origRequest.Accept = "application/vnd.hmrc.1.0+json"
        origRequest.Headers.Add("Authorization", "Bearer " + AccessToken)
        origRequest.Method = "GET"
        origResponse = DirectCast(origRequest.GetResponse(), HttpWebResponse)
        Dim reader As IO.StreamReader = New IO.StreamReader(origResponse.GetResponseStream(), Text.Encoding.Default)
        Dim content As String = reader.ReadToEnd()
        Dim myResults = JsonConvert.DeserializeObject(Of RootObligation)(content)


    Catch webEx As WebException
        Dim errorMessage As String = webEx.Message
        Dim errorStack As String = webEx.StackTrace
        Dim stream = webEx.Response.GetResponseStream()
        Dim reader = New StreamReader(stream)
        Dim ReadableError As String = reader.ReadToEnd().ToString
        Dim myResults = JsonConvert.DeserializeObject(Of RootError)(ReadableError)

    Catch ex As Exception
        Dim errorMessage As String = ex.Message
        Dim errorStack As String = ex.StackTrace

        Session("message") = "Error in submission ex:" + ex.Message + " " + errorStack
        Return RedirectToAction("VATSubmission", "Transaction")

    End Try

End Function
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

最终意识到 return 类型应该是 Object 而不是 Jarray。