如何在VB.net中获取JSON数组或对象的值?

时间:2016-04-28 04:54:55

标签: php json 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
                },
                .
                .
                .
                .
                .
            ]
        }
    ]

2 个答案:

答案 0 :(得分:4)

对于C#:

JObject jResults = JObject.Parse("JsonString");
String naming = jResults["sensors"]["naming "];
String unit = jResults["sensors"]["unit "];

对于VB:

Dim jResults As JObject = JObject.Parse("JsonString")
Dim naming As [String] = jResults("sensors")("naming ")
Dim unit As [String] = jResults("sensors")("unit ")

你可以这样做。

答案 1 :(得分:1)

以防万一人们想要使用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 

如果Json对象项不在数组中,而您只想要它返回的项

   For Each item As JProperty In data
       item.CreateReader()
             Dim customerId As String = ser("customerId")
             Dim deviceIdAs String = ser("deviceId")
   next

我使用'Chetan Sanghani'答案时出现错误,并使用字符串ex [String]附近的括号