【问题标题】:Accessing nested object in VB.net from newtonsoft json从newtonsoft json访问VB.net中的嵌套对象
【发布时间】:2016-08-14 17:52:38
【问题描述】:

首先,如果这已经发布,我们深表歉意。我花了一些时间研究,但没有找到解决方案。

我的目标是访问来自 vb.net 中对 Web 请求的各种 JSON 响应的数据。我在嵌套响应时遇到问题;一个例子:

Dim JSON as string = '{"url2": {"href": "https://example.com/test2/"}}'

我有这样的课程:

Public Class test1
    Public Class url2
        Public href As String
    End Class
End Class

反序列化 JSON:

Dim objURL1 As test1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Of test1)(JSON)

这似乎工作正常,但我根本不知道如何访问href 值,在本例中为“https://example.com/test2/”。

【问题讨论】:

    标签: vb.net json.net


    【解决方案1】:

    您混淆了两个概念:Nesting of .Net typesaggregation of instances of .Net objects。 (后面的链接适用于 c#,但也适用于 VB.NET。)

    您想要的是通过包含进行聚合,如下所示:

    Public Class Url2
        Public Property href As String
    End Class
    
    Public Class Test1
        Public Property url2 as Url2
    End Class
    

    然后访问href值做:

    Dim objURL1 = Newtonsoft.Json.JsonConvert.DeserializeObject(Of Test1)(JSON)
    dim href = objURL1.url2.href
    

    示例fiddle

    有关 .Net 中嵌套类型的更多背景信息,请参阅Why/when should you use nested classes in .net? Or shouldn't you?。如果您来自 Java,另请参阅 What are the fundamental differences between Java and C# in terms of inner/local/anonymous classes?,它解释了 .net 嵌套类型与 Java 内部类不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多