访问反序列化 JSON 并避免 var 声明

Access deserialize JSON and avoid var declaration

我是 vb 的新手(大约 2 小时前开始),我正在尝试将 php 应用程序转换为 vb 以解决一些不可避免的问题。

但是,我试图从服务器获得响应,该服务器将 returns 一个 JSON 字符串作为页面源(一切都很好,直到这里),我的问题是我不明白如何访问反序列化对象。
这是回应:

{
    "response":{
        "a":"boolean",
        "b":"string",
        "c":"string",
        "d":"string",
        "e":"string",
        "f":"string",
        "profile":{
            "h":"decimal",
            "i":"string",
            "l":"string",
            "m":"string",
            "n":"string",
            "o":"string",
            "p":"string",
            "q":"string"
        }
    }
}

当前vb代码:

    Public Class Form1
    ...
    Dim jsonResponse As String = New System.Net.WebClient().DownloadString(url)
    Dim r As LoginReturn = JsonConvert.DeserializeObject(Of LoginReturn)(jsonResponse)
    ...
End Sub

Public Class LoginItem
    Public a As Boolean
    Public apikey As String
    Public c As String
    Public d As String
    Public e As String
    Public f As String
    Public Property profile As List(Of LoginProfile)
End Class

Public Class LoginProfile
    Public h As Decimal
    Public i As String
    Public l As String
    Public m As String
    Public n As String
    Public o As String
    Public p As String
    Public q As String
End Class

Public Class LoginResponse
    Public Property response As List(Of LoginItem)
End Class

Public Class LoginReturn
    Public Property value As List(Of LoginResponse)
End Class

从所有这些信息中我只需要 apikey 所以我尝试使用这些

访问它
r.value.response.apikey
r.value(0).response.apikey

两个returns这个错误:

'apikey' is not a memeber of 'System.Collections.Generic.List(Of WindowsApplication1.LoginItem)'.

之前 php 我用过这个:

$r = json_decode(file_get_contents($url));
$_SESSION['a']=$r->response->apikey

所以我的问题是:

  1. 我如何访问该信息?
  2. 是否需要声明所有这些变量,即使我不需要它们?



编辑解决方案

'Get Json
Dim jsonResponse As String = New System.Net.WebClient().DownloadString(url)
'Parse Json
Dim r As JObject = JObject.Parse(jsonResponse)
'Access Json
GlobalVar.api = r("response")("apikey")

这将向您展示如何解析原始 JSON,以便您可以提取您感兴趣的部分。由于您只想要一件事,您可以使用 JObject.Parse 并放弃 classes 得到你想要的。

' you would get it from the webclient
Dim jstr As String = File.ReadAllText("C:\Temp\logresp.json")

Dim api = obj("response")("b")

要阅读其他内容,只需将键更改为您想要的任何项目。例如,读取 "q":

Dim QItem = obj("response")("profile")("q")

由于 qprofile 的 属性,它本身是 response 的子级,因此您必须深入挖掘。

如果您最终确实需要很多东西,您的 classes 不太适合解析为 class (DeserializeObject)。查看 JSON,您会发现没有名为 "APIKey" 的 属性。从位置上看,它被称为"b"。这可能是为了在这里发布而改变周围事物的神器,但我只能按照发布的内容进行。