为什么我不将Json反序列化为DataTable?

时间:2017-02-15 14:56:35

标签: c# asp.net json serialization

我使用下面的json字符串反序列化为DataTable

string json = "[{\"clientID\":\"1788\",\"projectID\":\"19\"}]";
var data = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

但我得到了以下异常

enter image description here

如果我尝试使用已成功反序列化的List反序列化。

var dat = JsonConvert.DeserializeObject<List<Client>>(json);

但我想使用DataTable进行反序列化。

如果我遗漏了任何内容,请建议我

先谢谢

2 个答案:

答案 0 :(得分:1)

你需要为你的JSON对象创建类,在我的例子中我可以给你举例..

public class TagValueConfig
{
    public string DisplayName { get; set; }
    public int MinTagValue { get; set; }
    public int MaxTagValue { get; set; }
}

然后你可以将它反序列化为对象数组

 TagValueConfig[] ObjTagConfigData = JsonConvert.DeserializeObject<TagValueConfig[]>(ConfigTagString);

一旦获得Deserialize数组,将其转换为DataTable格式..

或使用扩展方法。

希望这会有所帮助.. :)

答案 1 :(得分:0)

您无法将List<T>反序列化为DataTable。相反,您可以先获得List<T>,然后将其转换为DataTable

这:Converting a List to a DataTable可能是一个很好的注意点。

文章中的代码:

public static class ExtensionMethods
        {
        /// <summary>
        /// Converts a List to a datatable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(this IList<T> data)
            {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dt = new DataTable();
            for (int i = 0; i < properties.Count; i++)
                {
                PropertyDescriptor property = properties[i];
                dt.Columns.Add(property.Name, property.PropertyType);
                }
            object[] values = new object[properties.Count];
            foreach (T item in data)
                {
                for (int i = 0; i < values.Length; i++)
                    {
                    values[i] = properties[i].GetValue(item);
                    }
                dt.Rows.Add(values);
                }
            return dt;
            }
        }

使用文章中的通用代码,您可以执行以下操作:

var dat = JsonConvert.DeserializeObject<List<Client>>(json);

然后转换:

var dataTable = dat.ToDataTable();