【问题标题】:Why am i not deserialize the Json to DataTable? [duplicate]为什么我不将 Json 反序列化为 DataTable? [复制]
【发布时间】:2017-07-04 07:34:27
【问题描述】:

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

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

但我得到了以下异常

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

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

但我想使用 DataTable 反序列化。

如果我遗漏了什么,请建议我

提前致谢

【问题讨论】:

  • 请不要发布异常的屏幕截图,而是发布文本,包括堆栈跟踪。单击“查看详细信息...”时可以看到
  • 这个对象是否使用 DataTable 对象作为源进行了序列化?否则它将没有正确的序列化格式将其转换为 DataTable
  • 不能直接将 JSON 转成 system.DataTable 格式,需要设置相同的类。
  • 尝试删除外部方括号。或者在周围添加额外的数字括号。
  • 感谢您的建议,我已经尝试过这样但我仍然面临问题 string json = "{{\"clientID\":\"1788\",\"projectID\ ":\"19\"}}";

标签: c# asp.net json serialization


【解决方案1】:

您不能将 List&lt;T&gt; 反序列化为 DataTable。相反,您可以先获取List&lt;T&gt;,然后将其转换为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();

【讨论】:

    【解决方案2】:

    您需要为您的 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 格式..

    或使用扩展方法。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-16
      相关资源
      最近更新 更多