本文介绍了Json无法使用VB.net反序列化YouTube数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从YouTube上获得的响应中获取标题".我在第8行的位置12,即在行上得到以下错误:

I need to obtain the "title" from the response i get from Youtube.I get the following error at line 8, position 12, that is, at line:

"items": [

紧接在"["

我得到的错误是:

Exception: Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll ("Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'categoryid.Item' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'items', line 8, position 12."). Exception thrown: 'Newtonsoft.Json.JsonSerializationException' in Newtonsoft.Json.dll ("Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'categoryid.Item' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path 'items', line 8, position 12.")    2.61s       [12096] <No Name>

我有此代码:

 Dim m As IEnumerable(Of Rootobject) = JsonConvert.DeserializeObject(Of IEnumerable(Of Rootobject))(res)

具有以下JSON数据:

with this JSON data:

{
 "kind":"youtube#videoListResponse",
 "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/jznkhy3_Aws9VtommTkcdOYnAAk\"",
 "pageInfo":{
  "totalResults":1,
  "resultsPerPage":1
 },
 "items":[
  {
   "kind":"youtube#video",
   "etag":"\"m2yskBQFythfE4irbTIeOgYYfBU/M_wQmC4lQBaHJGxo79N7WlmqNr8\"",
   "id":"SSbBvKaM6sk",
   "snippet":{
    "publishedAt":"2009-04-15T20:31:11.000Z",
    "channelId":"UC2kTZB_yeYgdAg4wP2tEryA",
    "title":"Blur - Song 2",
    "description":"Blur 21 -- Celebrating 21 years of Blur. To find out more, click here:http://smarturl.it/blur21y\n\n#blur21\n            \nFollow Blur on Twitter:www.twitter.com/blurofficial \nFind Blur on Facebook:www.facebook.com/blur\n\nMusic video by Blur performing Song 2.",
    "thumbnails":{
     "default":{
      "url":"https://i.ytimg.com/vi/SSbBvKaM6sk/default.jpg",
      "width":120,
      "height":90
     },
     "medium":{
      "url":"https://i.ytimg.com/vi/SSbBvKaM6sk/mqdefault.jpg",
      "width":320,
      "height":180
     },
     "high":{
      "url":"https://i.ytimg.com/vi/SSbBvKaM6sk/hqdefault.jpg",
      "width":480,
      "height":360
     },
     "standard":{
      "url":"https://i.ytimg.com/vi/SSbBvKaM6sk/sddefault.jpg",
      "width":640,
      "height":480
     },
     "maxres":{
      "url":"https://i.ytimg.com/vi/SSbBvKaM6sk/maxresdefault.jpg",
      "width":1280,
      "height":720
     }
    },
    "channelTitle":"emimusic",
    "tags":[
     "Blur",
     "Song"
    ],
    "categoryId":"10",
    "liveBroadcastContent":"none",
    "localized":{
     "title":"Blur - Song 2",
     "description":"Blur 21 -- Celebrating 21 years of Blur. To find out more, click here:http://smarturl.it/blur21y\n\n#blur21\n            \nFollow Blur on Twitter:www.twitter.com/blurofficial \nFind Blur on Facebook:www.facebook.com/blur\n\nMusic video by Blur performing Song 2."
    }
   },
   "contentDetails":{
    "duration":"PT2M3S",
    "dimension":"2d",
    "definition":"sd",
    "caption":"false",
    "licensedContent":true,
    "regionRestriction":{
     "allowed":[
      "BY",
      "US"
     ]
    },
    "projection":"rectangular"
   }
  }
 ]
}

和这些类. Visual Studio 2015选项将这些课程粘贴为特殊课程.

and these classes. the classes are pasted as special with the visual studio 2015 option.

Public Class Rootobject
    Public Property kind As String
    Public Property etag As String
    Public Property pageInfo As Pageinfo
    Public Property items() As Item
End Class

Public Class Pageinfo
    Public Property totalResults As Integer
    Public Property resultsPerPage As Integer
End Class

Public Class Item
    Public Property kind As String
    Public Property etag As String
    Public Property id As String
    Public Property snippet As Snippet
    Public Property contentDetails As Contentdetails
End Class

Public Class Snippet
    Public Property publishedAt As Date
    Public Property channelId As String
    Public Property title As String
    Public Property description As String
    Public Property thumbnails As Thumbnails
    Public Property channelTitle As String
    Public Property tags() As String
    Public Property categoryId As String
    Public Property liveBroadcastContent As String
    Public Property localized As Localized
End Class

Public Class Thumbnails
    Public Property _default As _Default
    Public Property medium As Medium
    Public Property high As High
    Public Property standard As Standard
    Public Property maxres As Maxres
End Class

Public Class _Default
    Public Property url As String
    Public Property width As Integer
    Public Property height As Integer
End Class

Public Class Medium
    Public Property url As String
    Public Property width As Integer
    Public Property height As Integer
End Class

Public Class High
    Public Property url As String
    Public Property width As Integer
    Public Property height As Integer
End Class

Public Class Standard
    Public Property url As String
    Public Property width As Integer
    Public Property height As Integer
End Class

Public Class Maxres
    Public Property url As String
    Public Property width As Integer
    Public Property height As Integer
End Class

Public Class Localized
    Public Property title As String
    Public Property description As String
End Class

Public Class Contentdetails
    Public Property duration As String
    Public Property dimension As String
    Public Property definition As String
    Public Property caption As String
    Public Property licensedContent As Boolean
    Public Property regionRestriction As Regionrestriction
    Public Property projection As String
End Class

Public Class Regionrestriction
    Public Property allowed() As String
End Class

我需要做什么?预先感谢.

What i need to do?Thanks in advance.

推荐答案

您将收到该异常,因为您错误地声明了几个自动实现的数组属性.如 自动实现的属性(Visual Basic) 此类属性应声明如下,并且()数组指示符应作为返回类型的一部分:

You are getting that exception because you have declared several auto-implemented array properties incorrectly. As shown in Auto-Implemented Properties (Visual Basic) such properties should be declared as follows, with the () array indicator as part of the return type:

Public Property items As Item()

相反,您可以如下声明它们:

Instead you declare them as follows:

Public Property items() As Item

这声明了一个属性,该属性返回单个Item而不是它们的数组.附在属性名称上的()是可选的;对于无参数属性,这是多余的,但是对于采用参数的属性,参数列表将显示在此处.请参阅文档页面 属性声明 以获取详细信息.然后,Json.NET会在尝试将JSON数组反序列化为模型中的非数组属性之一时引发您看到的异常.

This declares a property returning a single Item rather than an array of them. The () attached to the property name is optional; for parameterless properties it is redundant but for properties taking parameters the argument list appears there. See the documentation page Property Statement for details. Then Json.NET throws the exception you see when attempting to deserialize a JSON array into one of the non-array properties in your model.

要解决此问题,应按如下所示修改您的三个类:

To fix this, three of your classes should be modified as follows:

Public Class Rootobject
    Public Property kind As String
    Public Property etag As String
    Public Property pageInfo As Pageinfo

    Public Property items As Item()   ' Fixed

End Class

Public Class Snippet
    Public Property publishedAt As Date
    Public Property channelId As String
    Public Property title As String
    Public Property description As String
    Public Property thumbnails As Thumbnails
    Public Property channelTitle As String

    Public Property tags As String()   ' Fixed

    Public Property categoryId As String
    Public Property liveBroadcastContent As String
    Public Property localized As Localized
End Class

Public Class Regionrestriction

    Public Property allowed As String()   ' Fixed

End Class

然后,由于items是一个数组,因此可以访问标题并将其放在列表中,因此可以使用 System.Linq.Enumerable :

Then, since the items are an array, to access the titles and put then in a list, you can use extension methods from System.Linq.Enumerable:

' Convert the json string to RootObject.
Dim root = JsonConvert.DeserializeObject(Of Rootobject)(json)

' Extract the list of titles.
Dim titles = root.items _
    .Select(Function(i) i.snippet.title) _
    .ToList()

' Get the first title in the list.
Dim firstTitle = titles.FirstOrDefault()

Console.WriteLine("First title = ""{0}""", firstTitle)

哪个打印出First title = "Blur - Song 2".

示例 VB.Net小提琴.

这篇关于Json无法使用VB.net反序列化YouTube数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:20