Good morning, today i was trying to convert my json to datatable.
This is what i\'m trying to do
Dim webclient_server7 As New System.Net.WebClien
First you need to remove this line:
Dim json_jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(json_result)
The downloaded string is already JSON, if you serialize it again you will turn it into an escaped JSON string literal, whereupon deserializing it returns the string - and not a DataTable as you want. This explains the error Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path '', line 1, position 9919: Json.NET parsed the entire json_jsonstring string as a single, escaped string literal.
Second, your JSON contains an outer root object like so:
{
"Table": [
{
"IdOwner": "Davide",
// Additional properties
},
// Additional rows.
]
}
Thus you need to introduce a root object with the necessary Table property to deserialize the DataTable into. You can do it with the following generic root:
Class RootObject(Of T)
Public Property Table As T
End Class
And then deserialize as follows:
Dim table = JsonConvert.DeserializeObject(Of RootObject(Of DataTable))(json_result).Table
Sample fiddle.
Or, if you don't care to create a root type, deserialize to a temporary Dictionary(Of string, DataTable):
Dim table = JsonConvert.DeserializeObject(Of Dictionary(Of string, DataTable))(json_result).Values.SingleOrDefault()
Sample fiddle #2:
You asked, I was wondering if making a sort of "substring" deleting the "{ Table:" part and the last } could work? Certainly it's possible but I would not recommend this. You would be manually duplicating some of the logic of a JSON parser. Let Json.NET do the work for you, it will handle whitespace and newlines correctly.