* json中的value的type有时候是个array,DataTable是不能写入这样的json的。但是由于业务需求有时候可能需要将json中的Array也写入DataTable。
* 解决方案是将DataTable中的Array的type改成string,或者直接将这样的value直接转成null。
* 以下有两个解决方法:
方法一:在JArray转化成DataTable的时候,在DataTable add Columns的时候,将数据中type是array的,将DataTable的Column的type设定成string。
* ConvertToDataTable
private DataTable ConvertToDataTable(JArray dataArr) { if (dataArr == null || dataArr.Count <= 0) { return new DataTable(); } DataTable result = new DataTable(); //headername var colnames = ((JObject)(dataArr.First)).Properties(); List<dynamic> columnNames = new List<dynamic>(); if (colnames == null || colnames.Count() <= 0) { return null; } foreach (var item in colnames) { JTokenType type = item.Value.Type; if (!columnNames.Contains(item.Name)) { columnNames.Add(item.Name); } //set Columns type result.Columns.Add(item.Name, convertJTokenTypeToType(type)); } //add detail foreach (JObject data in dataArr) { JObject jo = JObject.Parse(data.ToString()); DataRow row = result.NewRow(); foreach (var columnName in columnNames) { if (jo.Property(columnName) == null) { data.Add(columnName, ""); row[columnName] = data[columnName]; } else { row[columnName] = data[columnName]; } } result.Rows.Add(row); } if (result == null) { return new DataTable(); } return result; }
* set Columns type
private Type convertJTokenTypeToType(JTokenType jTokenType) { switch (jTokenType) { case JTokenType.Boolean: return typeof(bool); case JTokenType.Date: return typeof(DateTime); case JTokenType.Integer: return typeof(Int64); case JTokenType.Float: return typeof(float); case JTokenType.TimeSpan: return typeof(TimeSpan); default: return typeof(string); } }
方法二:Json转化为JArray后,在JArray转化成DataTable前,将value的type是array的,全部改成string。
private DataTable ConvertToDataTable(JArray dataArr) { if (dataArr == null || dataArr.Count <= 0) { return new DataTable(); } JArray changeType = new JArray(); for (int i = 0; i < dataArr.Count; i++) { JObject itemArr = new JObject(); foreach (dynamic item in dataArr[i]) { if (item.Value.Type == JTokenType.Array) { object value = item.Value.ToString(); JToken objValue = JToken.FromObject(value); JProperty obj = new JProperty(item.Name.ToString(), objValue); itemArr.Add(obj); } else if(item.Value.Type == null) { object value = item.Value.ToString(); JToken objValue = JToken.FromObject(value); JProperty obj = new JProperty(item.Name.ToString(), objValue); itemArr.Add(obj); } else { itemArr.Add(item); } } changeType.Add(itemArr); } //jarray to DataTable; DataTable? result = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(changeType)); if (result == null) { return new DataTable(); } return result; }
标签:return,JTokenType,dataArr,嵌套,Json,typeof,type,DataTable From: https://www.cnblogs.com/fishanan/p/16778633.html