fix(util): preserve complex JSON values in data tables

This commit is contained in:
SugarChes
2026-07-30 15:01:56 +08:00
parent 11e395aa0f
commit 5e6449cf1f
3 changed files with 238 additions and 0 deletions
+80
View File
@@ -9,6 +9,7 @@
******************************/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Data;
@@ -154,6 +155,85 @@ namespace Lskj.Util
return result;
}
/// <summary>
/// <para>说明:将可能包含对象或数组字段的网页行 JSON 转换为 DataTable</para>
/// <para>复杂字段所在列统一保留为字符串,纯标量列保持现有类型推断</para>
/// </summary>
/// <param name="json">顶层对象或对象数组 JSON</param>
/// <returns>DataTable.</returns>
public static DataTable ToDataTablePreservingComplexValues(string json)
{
if (string.IsNullOrWhiteSpace(json))
{
throw new ArgumentException("网页行 JSON 不能为空。", "json");
}
JToken root = JToken.Parse(json);
JArray rows;
if (root.Type == JTokenType.Array)
{
rows = (JArray)root;
}
else if (root.Type == JTokenType.Object)
{
rows = new JArray(root);
}
else
{
throw new JsonSerializationException("网页行 JSON 的顶层必须是对象或对象数组。");
}
HashSet<string> complexColumns = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (JToken rowToken in rows)
{
if (rowToken.Type != JTokenType.Object)
{
throw new JsonSerializationException("网页行 JSON 数组中的每一项都必须是对象。");
}
foreach (JProperty property in ((JObject)rowToken).Properties())
{
if (property.Value.Type == JTokenType.Object || property.Value.Type == JTokenType.Array)
{
complexColumns.Add(property.Name);
}
}
}
foreach (JObject row in rows.Children<JObject>())
{
foreach (JProperty property in row.Properties().ToList())
{
if (!complexColumns.Contains(property.Name)
|| property.Value.Type == JTokenType.Null
|| property.Value.Type == JTokenType.Undefined)
{
continue;
}
string text;
if (property.Value.Type == JTokenType.Object || property.Value.Type == JTokenType.Array)
{
text = property.Value.ToString(Formatting.None);
}
else if (property.Value.Type == JTokenType.String)
{
text = property.Value.Value<string>();
}
else
{
JValue scalar = property.Value as JValue;
text = scalar == null || scalar.Value == null
? null
: Convert.ToString(scalar.Value, CultureInfo.InvariantCulture);
}
property.Value = text == null ? JValue.CreateNull() : new JValue(text);
}
}
return JsonConvert.DeserializeObject<DataTable>(rows.ToString(Formatting.None));
}
/// <summary>
/// <para>说明:</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-10-23 </para>