在vb.net中反序列化嵌套的json

时间:2012-09-26 18:43:09

标签: vb.net json deserialization

我是json的新手,正在努力将一些嵌套的json反序列化为一个对象。外部对象工作正常,但我没有得到内部对象的任何值。我尝试了几种解决方案,包括使用列表对象,集合,datacontractserializer,但似乎没有任何工作。我想我可能错过了一些明显的东西。这就是我现在所拥有的:

json字符串如下所示: { “类型”: “查找”, “消息”: “成功”, “版本”:0.1, “用户”:{ “LOGINNAME”: “用户名”, “供应商”:空}}

我的代码如下:

<Serializable()> Public Class LookupReturn
    Private _Type As String = ""
    Private _Message As String = ""
    Private _Version As String = ""
    Private _user As New jsonUser


    Public Property Type() As String
        Get
            Return _Type
        End Get
        Set(ByVal value As String)
            _Type = value
        End Set
    End Property

    Public Property Message() As String
        Get
            Return _Message
        End Get
        Set(ByVal value As String)
            _Message = value
        End Set
    End Property

    Public Property Version() As String
        Get
            Return _Version
        End Get
        Set(ByVal value As String)
            _Version = value
        End Set
    End Property

    Public Property Userobj() As jsonUser
        Get
            Return _user
        End Get
        Set(ByVal value As jsonUser)
            _user = value
        End Set
    End Property

End Class

<Serializable()> Public Class jsonUser
    Private _loginName As String = ""
    Private _vendor As String = ""

    Public Property loginName() As String
        Get
            Return _loginName
        End Get
        Set(ByVal value As String)
            _loginName = value
        End Set
    End Property

    Public Property vendor() As String
        Get
            Return _vendor
        End Get
        Set(ByVal value As String)
            _vendor = value
        End Set
    End Property

End Class

Dim _Json As New JavaScriptSerializer()
Dim _Message as string = "{"type":"lookup","message":"Success","version":0.1,"user"{"loginName":"username","vendor":null}}"
Dim returnData As LookupReturn = _Json.Deserialize(Of LookupReturn)(_Message)

我正在查找LookupReturn对象的类型,消息,版本值中的数据,并且它返回用户项的对象,但loginName的值是一个空字符串。

任何帮助将不胜感激!

谢谢!

1 个答案:

答案 0 :(得分:0)

在使用了这个之后,我意识到问题是我的嵌套对象没有被命名,因为它应该在我的代码的Get / Set部分中。因为我在jSon中调用了它“Userobj”而不是“user”,所以反序列化器无法正常工作。我把名字改为“用户”,一切运作良好!