Having an issue getting a JSON string to convert into a C# Datatable...
Here is an example of the JSON string that gets returned to me code from an API
{
"Code": 0,
"Result": [
{
"ID": 1,
"Reference": "101",
"Asset": 200,
"Event": 1,
"DateEventStart": "2/10/2017 9:08:33 PM",
"DateEvent": "2/11/2017 1:00:14 AM"
}
]
}
So that comes in from the API and I read it, then attempt to create a DataTable like this
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var encoding = Encoding.GetEncoding(response.CharacterSet);
var responseStream = response.GetResponseStream();
var reader = new StreamReader(responseStream, encoding);
responsetext = reader.ReadToEnd();
var table = JsonConvert.DeserializeObject<DataTable>(responsetext);
However this gives the following error:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1
I'm new to dealing with JSON in C# so any help appreciated. I think that my string is invalid in some way in terms of getting it to be parsed, but I don't know. If there is more info required let me know
EDIT: Ok I followed the link that Xingxing Qiao put - makes sense. I now get a different error which I think is due to what I've put into the class that the JSON gets deserialised into -
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[WindowsFormsApplication7.TrackingResponse]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Code', line 1, position 8.
Here is that class...is it because I don't include 'Code' and 'Result' from the JSON (see string above)
public class TrackingResponse
{
public string ID { get; set; }
public string Reference { get; set; }
public string Asset { get; set; }
public string Event { get; set; }
public string DateEventStart { get; set; }
public string DateEvent { get; set; }
}