在vb.net中获取令牌值

时间:2019-02-08 10:48:20

标签: json vb.net

我希望在vb.net中循环以下Json并提取 导演给出的吉恩和家人

 "director": {
    "lineage": null,
    "given": "Na",
    "honourific": null,
    "family": "Jes"
  },
  "creators": [
    {
      "name": {
        "lineage": null,
        "given": "Ju",
        "honourific": null,
        "family": "Pa"
      },
      "id": "ju-anne.n@etu.un-.fr"
    }
  ],

语音代码:

    For k = 0 To imax
                    creators = jsonData(k)("creators")

                    director = jsonData(k)("director")

                    'Dim c As New Object

                    Dim result2 As String = Replace(director.ToString, "{[", "")
                    result2 = Replace(result2.ToString, "]}", "")


                    Dim n As JObject = JObject.Parse(result2)
                    Dim result As List(Of JToken) = n.Children().ToList

                    For Each item As JProperty In result
                        item.CreateReader()

                        Select Case item.Name
                            Case "given"

                                'strgiven = item.Value.ToString
                                Dim strgiven As String

                                For Each subitem As JObject In item.Values
                                    strgiven = subitem("given")

                                Next

                            Case "family"

                                Dim strfamily As String

                                For Each subitem As JObject In item.Values
                                    strfamily = subitem("family")
                                Next

                        End Select

                    Next
                Next

我一直希望它能给我和家人,但在调试时会显示此错误: {“无法将类型为'Newtonsoft.Json.Linq.JValue'的对象强制转换为类型为'Newtonsoft.Json.Linq.JObject'。”}

1 个答案:

答案 0 :(得分:0)

这将为您服务

For Each subitem As JValue In item.Values
  strgiven = subitem.Value As String
Next

这样做的原因是,由于“给定”中的值为“ Ju”,因此它是字符串,而不是对象。因此,它不能将其转换为应该表示JSON对象的JObject。这就是错误告诉您的内容。您作为JObject试图将其强制为JObject,但这是不可能的,因为该值只是一个简单的字符串。 JSON.NET使用JValue类来表示那些-再次查看,错误消息告诉您应该使用哪个类,因为它告诉您要强制进入JObject的变量实际上是JValue。而且,一旦有了JValue,就可以简单地访问其“ Value”属性并将其转换为所需的类型(在这种情况下为字符串)