1

我有一种感觉,我只是在这里做了一个小小的疏忽,我认为第二(或第三)双眼睛可以帮助解决这个问题。这是我所做的:

  1. 向网络服务发出请求
  2. 收到来自该 Web 服务的 JSON 响应
  3. 将该 JSON 读入字符串

该字符串成功包含 JSON 输出。然而,这就是事情变得困难的地方。我创建了一个公共类,我想将我的反序列化 JSON 转换为该类。但是,当我尝试将 JSON 字符串转换为一个类(使用 JSON.NET)时,我收到以下错误。

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type  m      'Sandbox.youtube+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.

JSON 看起来像这样:

{
"kind": "youtube#searchListResponse",
"etag": "\"Fn7tolrWrLXf7uknBpwCU9OfMA8/AgytE2CN3Aj3J6OFJ5iDqg8-Hbw\"",
"pageInfo": {
 "totalResults": 1000000,
 "resultsPerPage": 50
     },
  "nextPageToken": "CDIQAA",
  "items": [
   {
  "kind": "youtube#searchResult",
   "etag": "\"Fn7tolrWrLXf7uknBpwCU9OfMA8/mQk0CDCRDq-8Xy5YSW9FLLA7B3g\"",
   "id": {
"kind": "youtube#video",
"videoId": "BJ2q017EL08"
}
 }

(复制/粘贴时我可能错过了几个括号)

我的公开课是这样的:

Public Class Rootobject

    Public Property kind As String
    Public Property etag As String
    Public Property pageInfo As Pageinfo
    Public Property nextPageToken As String
    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 Idprop
End Class

Public Class Idprop
    Public Property kind As String
    Public Property videoId As String
End Class

我尝试这样投射:

Dim ent As Rootobject = TryCast(Json.JsonConvert.DeserializeObject(Of Rootobject)(webresponse), Rootobject)

任何想法都非常感谢!

一切顺利,乔丹

4

1 回答 1

2

更改此行:

Public Property items() As Item

对此:

Public Property items As List(Of Item)
于 2013-06-20T18:28:55.457 回答