.net 从Twitter趋势API反序列化Json

qlzsbp2j  于 2022-12-20  发布在  .NET
关注(0)|答案(2)|浏览(102)

我尝试反序列化这个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
      }
    ]
  }
]

所以我创建了3个类:

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

我试过反序列化:

Dim result As TwitterTrendApiResponse = JsonConvert.DeserializeObject(strMyJsonToDeserialize)

但是我遇到了一个异常“无法将类型为”Newtonsoft.json.linq.JArray“的对象转换为TwitterTrendApiResponse类型。我哪里出错了?”

gv8xihay

gv8xihay1#

事实上,你的json是一个对象列表,而不仅仅是一个对象。

Dim result As  List( Of ResponseListElements) = JsonConvert.DeserializeObject(Of List( Of ResponseListElements))(strMyJsonToDeserialize);

并修正课程

Public Class ResponseListElements
        Public Property trends As Trend()
        Public Property as_of As DateTime
        Public Property created_at As DateTime
        Public Property locations As Location()
    End Class

 Public Class Trend
        Public Property name As String
        Public Property url As String
        Public Property promoted_content As Object
        Public Property query As String
        Public Property tweet_volume As Integer?
    End Class

    Public Class Location
        Public Property name As String
        Public Property woeid As Integer
    End Class
r3i60tvu

r3i60tvu2#

你必须改变这一点:

Dim result As TwitterTrendApiResponse = JsonConvert.DeserializeObject(strMyJsonToDeserialize)

在:

Private myDeserializedClass As Object = JsonConvert.DeserializeObject(Of List(Of TwitterTrendApiResponse))(strMyJsonToDeserialize)

正如您在JSON数据中所看到的,根节点是一个数组。然后,如果返回的对象是数组或单个类,请注意其类型,以便正确声明。AS List(Of TwitterTrendApiResponse)AS TwitterTrendApiResponse

相关问题