Question

I'm kinda new to manipulating JSON format data retrieved through an API. I'm using JSON.NET to deserealize and for most JSON format data, it works, however, when I try to retrieve data from ETSY in JSON format, it gives an error...

Unexpected JSON token while reading DataTable: StartObject

This is the JSON data I am trying to get into a datatable...It's a sample data from ETSY's account.

{
    "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":{}
}

Here is my current code...

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

Can anybody help me sort this out? Thank you very much.

Was it helpful?

Solution

In order to deserialize into a DataTable or DataSet, Json.Net requires a very specific format as seen in this example from the documentation. Your JSON does not conform to this format, therefore it does not work. This does not mean you can't use Json.Net, it just means that you need to choose some other way to deserialize.

One way is to create strongly typed classes, and deserialize into those:

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

Then:

Dim root As RootObject = JsonConvert.DeserializeObject(Of RootObject)(json)

Alterntatively, you could deserialize into a JObject and use Json.Net's LINQ-to-JSON API to navigate and extract the data you need. Here is an example that might help with that. There are many other examples in the documentation as well as here on StackOverflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top