0

我只是想找出反序列化从 3rd 方 api 调用返回的 json 字符串的最佳方法。我读到 ServiceStack 很快,所以想尝试一下。没有经验,这是我所做的:

  1. 打开 Visual Studio 2013
  2. 创建新项目 Windows 窗体应用程序
  3. 安装 ServiceStack.Text(基于https://servicestack.net/download
  4. 添加了一个按钮(btnView)和文本框(txtOutput)
  5. 将代码添加到 btnView_Click 事件

           Private Sub btnView_Click(sender As Object, e As EventArgs) Handles btnView.Click
    
        Me.Cursor = Cursors.WaitCursor
    
        Dim wp As New WebPost 'this allows to pass url and return results
        wp.URL = "xxxx"
        Dim sJSONRetVal As String = wp.Request(String.Empty, True)
    'sJSONRetVal return values looks like the following:
    '{"complaints":[{"feedback_type":"abuse","subject":"Sales Agent Position"},{"feedback_type":"abuse","subject":"Sales Agent Position"}],"message":"OK","code":0}
    
    
        'ServiceStack.Text example
        Dim t As SMTP_Complaints = ServiceStack.Text.JsonSerializer.DeserializeFromString(Of SMTP_Complaints)(sJSONRetVal)
    
        'For Each xi As SMTP_Complaints In t
        '    txtOutput.Text &= xi.mail_from & vbCrLf
        'Next
    
        wp = Nothing
    
        txtOutput.Text = t.ToString
    
        Me.Cursor = Cursors.Default
    
    End Sub
    
    Public Class SMTP_Complaints
    
    Dim _feedback_type As String = ""
    Dim _subject As String = ""
    
    Public Property feedback_type As String
        Get
            Return _feedback_type
        End Get
        Set(value As String)
            _feedback_type = value
        End Set
    End Property
    
    Public Property subject As String
        Get
            Return _subject
        End Get
        Set(value As String)
            _subject = value
        End Set
    End Property
    End Class
    

以上似乎没有得到任何数据。我将如何遍历返回的数据并从两个实例返回数据?只是不确定我需要如何设置它来读取 json 数据然后能够输出。

4

1 回答 1

3

基于返回的 JSON:

{"complaints":[{"feedback_type":"abuse","subject":"Sales Agent Position"},{"feedback_type":"abuse","subject":"Sales Agent Position"}],"message":"OK","code":0}

您将需要两个 DTO 来反序列化此结果。

我在这里使用了自动实现的属性来简化代码的复杂性。如果您使用旧版本的 VB,则需要扩展这些以包含带有 get 和 set 方法的支持字段。

Public Class SMTP_Complaint
    Public Property feedback_type As String
    Public Property subject As String
End Class

Public Class SMTP_ComplaintsResponse
    Public Property complaints As SMTP_Complaint()
    Public Property message As String
    Public Property code As Integer
End Class

您需要该SMTP_ComplaintsResponse课程,因为您的投诉包含在 JSON 响应中。

然后反序列化响应:

Dim response = JsonSerializer.DeserializeFromString(Of SMTP_ComplaintsResponse)(sJSONRetVal)

然后可以访问您的投诉:

For Each complaint As var In response.complaints
    Console.WriteLine("Type: {0}, Subject {1}", complaint.feedback_type, complaint.subject)
Next
于 2014-06-20T08:28:03.727 回答