I tried to deserialize this JSON:
[
{
"trends": [
{
"name": "#GiftAGamer",
"url": "http://twitter.com/search?q=%23GiftAGamer",
"promoted_content": null,
"query": "%23GiftAGamer",
"tweet_volume": null
},
{
"name": "#AskCuppyAnything",
"url": "http://twitter.com/search?q=%23AskCuppyAnything",
"promoted_content": null,
"query": "%23AskCuppyAnything",
"tweet_volume": 14504
}
],
"as_of": "2020-11-20T19:37:52Z",
"created_at": "2020-11-19T14:15:43Z",
"locations": [
{
"name": "Worldwide",
"woeid": 1
}
]
}
]
So I’ve created 3 classes:
Public Class TwitterTrendApiResponse
Public Property ttd As List(Of TwitterTrendDatas)
Public Property datAsOf As String
Public Property datCreatedAt As String
Public Property ttl As List(Of TwitterTrendLocation)
End Class
Public Class TwitterTrendLocation
Public Property strName As String
Public Property intWoeid As String
End Class
Public Class TwitterTrendDatas
Public Property strName As String
Public Property strUrl As String
Public Property strPromotedContent As String
Public Property strQuery As String
Public Property intVolume As String
End Class
and i’ve tried deserialize with:
Dim result As TwitterTrendApiResponse = JsonConvert.DeserializeObject(strMyJsonToDeserialize)
But I’ve got an exeception "Unable to cast object of type ‘Newtonsoft.Json.Linq.JArray’ to type TwitterTrendApiResponse. Where did i go wrong?
2
Answers
You have to change this:
In:
As you can see at the JSON data the root node is an array.
THen take care of type of returned object if it is an array or a single class, to declare it properly.
AS List(Of TwitterTrendApiResponse)
orAS TwitterTrendApiResponse
as a matter of fact your json is a list of objects, not just an object. So try this
and fix the classes