【发布时间】:2021-04-12 21:59:49
【问题描述】:
我的程序通过 Web API 访问数据并获取 JSON 格式的数据。响应例如:
{
"response":{
"stationId":"24026900",
"prices":[
{
"name":"Aral Super E10",
"price":"146,90",
"currency":"EUR",
"id":"001131",
"sort":"21"
},
{
"name":"Aral Super 95",
"price":"152,90",
"currency":"EUR",
"id":"001040",
"sort":"22"
},
{
"name":"Aral Ultimate 102",
"price":"172,90",
"currency":"EUR",
"id":"001255",
"sort":"24"
},
{
"name":"Aral Diesel",
"price":"130,90",
"currency":"EUR",
"id":"004002",
"sort":"30"
},
{
"name":"Aral Ultimate Diesel",
"price":"150,90",
"currency":"EUR",
"id":"004267",
"sort":"31"
},
{
"name":"Aral LKW Diesel",
"price":"130,90",
"currency":"EUR",
"id":"004010",
"sort":"32"
}
],
"lastUpdate":"202104122030",
"disabled":"false",
"openNow":"Wir haben f\u00fcr Sie ge\u00f6ffnet."
}
}
我该怎么做?访问深度嵌套的数据,例如 "price":"172,90"。
我的结构是这样的:
Dim sJSON As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim PriceLastValue As String = funcGetPriceInfo("response") 'How to get access to deeper nested data here?
'
'Every key except "response" throws an exception
'
MsgBox(PriceLastValue.ToString)
End Sub
Private Function funcGetPriceInfo(ByVal sVal As String) As String
Dim JSONSerializer As New System.Web.Script.Serialization.JavaScriptSerializer
sJSON = ReadStreamFromWeb.ReadFileFromWeb_WebRequest("http://ap.aral.de/api/v2/getStationPricesById.php?stationId=24026900")
Dim dictJSON As Dictionary(Of String, Object) = JSONSerializer.Deserialize(Of Dictionary(Of String, Object))(sJSON)
Return dictJSON(sVal).ToString
End Function
【问题讨论】:
-
这是一个简单的结构。 Root 对象
response包含 5 个属性。prices属性是Price对象的数组或列表。您可以通过索引访问数组中的每个对象。 -- 顺便说一句,您正在使用错误的编码读取 JSON 响应(请参阅openNow属性值,Wir haben f\u00fcr应该是Wir haben für)。您的 JSON 是 UTF-8 编码的。 -- 您可能应该将此 JSON 反序列化为类模型。 -- 需要使用JavaScriptSerializer吗?
标签: json vb.net javascriptserializer