如何在 VB.net 中获取 JSON 数组或对象的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36905546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get value of JSON array or object in VB.net?
提问by NajLinus
I have JSON file having following data. I just want to get the data of "naming" and "unit". Please assist me how to do this in VB.net?
我有包含以下数据的 JSON 文件。我只想获取“命名”和“单位”的数据。请帮助我如何在 VB.net 中做到这一点?
[
{
"customerId": "999",
"deviceId": "XXX999",
"searchDeviceId": "D_XXX999",
"utc": "2016-04-28T03:37:00.000Z",
"lat": 22.5691,
"lng": 120.3058,
"sensors": [
{
"naming": "ABC123",
"factor": null,
"unit": "k",
"period": null
},
{
"naming": "XYZ123",
"factor": null,
"unit": "c",
"period": null
},
.
.
.
.
.
]
}
]
回答by Chetan Sanghani
For C# :
对于 C#:
JObject jResults = JObject.Parse("JsonString");
String naming = jResults["sensors"]["naming "];
String unit = jResults["sensors"]["unit "];
For VB:
对于 VB:
Dim jResults As JObject = JObject.Parse("JsonString")
Dim naming As [String] = jResults("sensors")("naming ")
Dim unit As [String] = jResults("sensors")("unit ")
You can achieve like this.
你可以这样实现。
回答by DJN
Just in case people are looking to loop through multiple JSON Array or Object in vb.net using Newtonsoft.Json.Linq
以防万一人们希望使用 Newtonsoft.Json.Linq 在 vb.net 中循环遍历多个 JSON 数组或对象
request = url
request.Headers.Add("Authorization", "Bearer " + accessToken)
'Get response
response = DirectCast(request.GetResponse(), HttpWebResponse)
' Get the response stream into a reader
reader = New StreamReader(response.GetResponseStream())
Dim JSONresponseFromServer As String = reader.ReadToEnd()
' Parse the content into a json object
Dim json As String = JSONresponseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "sensors" 'each record is inside the entries array
For Each Entry As JObject In item.Values
Dim naming As String = Entry("naming ").ToList.Item(0)
Dim factor As String = Entry("factor").ToList.Item(0)
' you can continue listing the array items untill you reach the end of you array
Next
End Select
Next
If the Json object item is not in an array and you just want the items it returns
如果 Json 对象项不在数组中,而您只想要它返回的项
For Each item As JProperty In data
item.CreateReader()
Dim customerId As String = ser("customerId")
Dim deviceIdAs String = ser("deviceId")
next
I was getting an error using the 'Chetan Sanghani' answer with the brackets around string ex [String]
我在使用“Chetan Sanghani”答案时出现错误,并在字符串 ex [String] 周围加上括号

