我正在尝试将JSON文本序列化为DataTable,如下所示。
List<Dictionary<string, string>> list =
JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(jsonText);
DataTable dTable;
dTable = (from p in list select p).CopyToDataTable();
我收到以下错误。我该如何解决?
错误:
Cannot deserialize JSON object into type
'System.Collections.Generic.List`1[System.Collections.Generic.Dictionary`2
[System.String,System.String]]'.
答案 0 :(得分:6)
这对我有用:
using Newtonsoft.Json;
string json = "[{"clientID":"1788","projectID":"19"},{"clientID":"1789","projectID":"24"},{"clientID":"1790","projectID":"24"},{"clientID":"1790","projectID":"23"},{"clientID":"1790","projectID":"21"}]";
DataTable tester = (DataTable) JsonConvert.DeserializeObject(json, (typeof(DataTable)));
答案 1 :(得分:1)
public object Deserialize(string jsonText, Type valueType)
{
try
{
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonText);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, valueType);
reader.Close();
return result;
}
catch (Exception ex)
{
throw ex;
}
}