我有一个具有以下结构的 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[]A的元素,并将其添加到预先设计的数据表中。我的问题是,使用此功能后,性能会受到影响,因为在大多数情况下,从 API 检索的数据> 10000 个值。
有没有什么具体的方法可以在c#中以最有效的方式将这种JSON格式转换为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
祝你好运
关于c# - JToken 数组到数据表 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58485744/