有得到一個JSON字符串轉換成C#的DataTable的問題...問題JSON字符串轉換爲DataTable的C#
這裏是被從API返回我的代碼JSON字符串的例子
{
"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"
}
]
}
所以從API進來,我讀它,然後嘗試創建這樣
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);
一個DataTable然而,這提供了以下錯誤:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1
我新來處理JSON在C#中,所以任何幫助表示讚賞。我認爲我的字符串在某些方面無法解析,但我不知道。如果有更多的信息需要讓我知道
編輯: 好吧,我跟着星星喬放的鏈接 - 是有道理的。我現在得到一個不同的錯誤,我想是因爲我已經把進級了JSON被deserialised成 -
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.
這裏是一個類......是不是因爲我不包括'守則」和‘從JSON結果’(見上面的字符串)
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; }
}
檢查此[convert-json-to-datatable](http://stackoverflow.com/questions/11981282/convert-json-to-datatable) –
看起來像[從Json字符串反序列化嵌套的DataSet與Json.NET](https://stackoverflow.com/a/42090584/3744182)。正如在那個答案中,你需要一個包裝器根對象來包含你的'DataTable'。這是否足以回答您的問題,還是您需要特定的根對象? – dbc
謝謝@XingxingQiao,看看我上面的更多評論 – reviloSlater