将属性为T的类与json相互转换

时间:2019-01-31 09:20:30

标签: vb.net

我有一个类(MyMessage),它具有类型T的名为“设置”的属性。

我需要将MyMessage转换为json,通过TCP发送,当我收到它时,我需要测试Type T是什么类,然后将接收到的json转换为MyMessage Of T类。

到目前为止,这是我的代码-SendMessage和MessageRecieved函数无法正常工作...,我需要您的帮助:)...

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim t As New MyMessage(Of MyMessageSettingsText)
        t.Settings.Text = "Yes"
        Call SendMessage(t)

        Dim n As New MyMessage(Of MyMessageSettingsNumber)
        n.Settings.Number = 1
        Call SendMessage(n)
    End Sub

    Private Sub SendMessage(msg As MyMessage)
        Dim json As String = Newtonsoft.Json.JsonConvert.SerializeObject(msg)
        ' Do send using tcp etc
    End Sub

    Private Sub MessageRecieved(msgJson As String) ' A json string recived from a tcp server
        Dim msg As MyMessage = DirectCast(Newtonsoft.Json.JsonConvert.DeserializeObject(Of MyMessage)(msgJson), MyMessage)
        If TypeOf (msg.Settings) Is MyMessageSettingsText Then
            Dim t As MyMessage(Of MyMessageSettingsText) = CType(msg, MyMessage(Of MyMessageSettingsText))
            ' do something with t
        End If
    End Sub    
End Class


Public MustInherit Class MyMessageSettingsBase
End Class


Public Class MyMessageSettingsText
    Inherits MyMessageSettingsBase
    Public Property Text As String
End Class


Public Class MyMessageSettingsNumber
    Inherits MyMessageSettingsBase
    Public Property Number As Integer
End Class


Public Class MyMessage(Of T As {New})
    Public Property Name As String
    Public Property Settings As New T
End Class

0 个答案:

没有答案