我有一个具有以下结构的JSON结果:
{
"property1":1,
"property2":[[1,"A"],[2,"B"],[3,"C"],...] // Possible to get >10000 values
}
使用上述 JSON 数据格式,我只对从包含数组值数组的property2中获取数组值并将其转换为数据表感兴趣。
上面的JSON结果来自外部WEB API,这是我目前拥有的:
var jsonResponse = API.RetrieveData();
JObject json = JObject.Parse(jsonResponse);
JToken[] A = json["property2"].ToArray();
从逻辑上讲,我可以逐列循环 Array [] 的元素并将其添加到预先设计的数据表中。我的问题是,使用它时,性能会受到影响,因为在大多数情况下,从 API 检索的数据> 10000 个值。
是否有任何特定方法可以用最有效的方式将这种 JSON 格式转换为 c# 中的 DataTable?
提前谢谢你。
我有更好更快的方法给你
步骤 1
创建一个类似于 json 结构的类
public class JsonClass
{
public string property1 { get ; set; }
public List<Dictionary<int,string>> property2 { get ; set; }
}
步骤 2
使用 Newtonsoft 并将 json 输入反序列化为 json 匹配类
JsonClass jsonClass = JsonConvert.DeserializeObject<JsonClass>(jsonInputString);
步骤 3
如果您使用的是 WPF,只需使用
datatable.ItemSource = jsonClass ;
如果您使用的是Winform,请使用BindingSource Component。
BindingSource binding = new BindingSource();
binding.DataSource = jsonClass;
datatable.DataSource = binding;
结果可能是
property1 | property2
---------------------------------------
"A" | Collection
祝你好运