如何根据JSON填充字典中定义的对象变量?

时间:2012-06-13 11:39:00

标签: vb.net json

好的,这个问题听起来有点令人困惑,所以我会尝试用一个例子来解释它。

假装你有这样一个对象:

Class Something
    Private varX As New Integer
    Private varY As New String

'[..with the associated property definitions..]

    Public Sub New()
    End Sub

End Class

还有另一个:

Class JsonObject
    Inherits Dictionary(Of String, String)

    Public Function MakeObject() As Object 'or maybe even somethingObject 
        Dim somethingObject As New Something()

        For Each kvp As KeyValuePair(Of String, String) In Me
            'Here should happen something to use the Key as varX or varY and the Value as value for the varX or varY
            somethingObject.CallByName(Me, kvp.Key, vbGet) = kpv.Value

        Next

        return somethingObject
    End Function

End Class

我从previous question of myself

获得了'CallByMe()'函数

1 个答案:

答案 0 :(得分:0)

CallByName与您尝试使用它的方式不同。查看文档,它会告诉您在这种特殊情况下正确的用法是

CallByName(Me, kvp.Key, vbSet, kpv.Value)

但是,函数CallByName是所有设备都不支持的VB库的一部分(特别是它不包含在.NET Mobile框架中),因此最好不要使用它。 / p>

使用适当的反射稍微复杂一点,但保证可以在所有平台上运行。

Dim t = GetType(Something)
Dim field = t.GetField(kvp.Key, BindingFlags.NonPublic Or BindingFlags.Instance)
field.SetValue(Me, kvp.Value)