我很擅长操纵通过API检索的JSON格式数据。我使用JSON.NET来实现deserealize,对于大多数JSON格式数据,它可以工作,但是,当我尝试以JSON格式从ETSY检索数据时,它会出错...
Unexpected JSON token while reading DataTable: StartObject
这是我试图进入数据表的JSON数据......它是来自ETSY帐户的样本数据。
{
"count":1,
"results": [{
"user_id":5029420,
"login_name":"EtsyStore",
"creation_tsz":1282269739,
"referred_by_user_id":null,
"feedback_info": {
"count":3038,
"score":100
}
}],
"params": {
"user_id":"etsystore"
},
"type":"User",
"pagination":{}
}
这是我目前的代码......
Dim webClient As New System.Net.WebClient
Dim json As String = webClient.DownloadString("https://openapi.etsy.com/v2/users/etsystore?api_key=apikey")
Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)
DataGridView1.DataSource = table
有人可以帮我解决这个问题吗?非常感谢你。
答案 0 :(得分:2)
为了反序列化为DataTable
或DataSet
,Json.Net需要一种非常具体的格式,如example from the documentation所示。您的JSON不符合此格式,因此它不起作用。这并不意味着您不能使用Json.Net,它只是意味着您需要选择其他方式来反序列化。
一种方法是创建强类型类,并反序列化为:
Public Class RootObject
Public Property count As Integer
Public Property results As List(Of Result)
Public Property params As Params
Public Property type As String
Public Property pagination As Pagination
End Class
Public Class Result
Public Property user_id As Integer
Public Property login_name As String
Public Property creation_tsz As Integer
Public Property referred_by_user_id As Object
Public Property feedback_info As FeedbackInfo
End Class
Public Class FeedbackInfo
Public Property count As Integer
Public Property score As Integer
End Class
Public Class Params
Public Property user_id As String
End Class
Public Class Pagination
End Class
然后:
Dim root As RootObject = JsonConvert.DeserializeObject(Of RootObject)(json)
另外,您可以反序列化为JObject
并使用Json.Net的LINQ-to-JSON API来导航和提取所需的数据。以下an example可能对此有所帮助。文档中还有许多其他示例以及StackOverflow。