gpt4 book ai didi

c# - 将嵌套的 JSON 数据解析为 DataTable

转载 作者:行者123 更新时间:2023-11-30 12:26:30 33 4
gpt4 key购买 nike

我需要解析下面嵌套到数据表中的一些 JSON 数据。 3 个组中每个组的“属性”字段都包含标题、值和优先级的内部数据。

[{
"Title": "OVERVIEW",
"Priority": 1,
"attributes": [{
"Title": "Type",
"Value": "MacBook Pro",
"Priority": 1
},
{
"Title": "Operating system",
"Value": "OS X Mountain Lion",
"Priority": 2
},
{
"Title": "Processor",
"Value": "Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)",
"Priority": 3
},
{
"Title": "Storage",
"Value": "500 GB HDDM 5400 rpm",
"Priority": 4
}]
},
{
"Title": "SPECIFICATION",
"Priority": 2,
"attributes": [{
"Title": "RAM",
"Value": "4 GB DDR3",
"Priority": 1
}]
},
{
"Title": "SCREEN",
"Priority": 3,
"attributes": [{
"Title": "Screen size",
"Value": "13\"",
"Priority": 1
}]
}]

我意识到我需要先反序列化 JSON 数据,

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);

public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();

for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];

foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}

但不确定从那里去哪里,因为上面只考虑了正常的 JSON 数据。任何帮助将不胜感激。

最佳答案

使用这个类反序列化数据

         public class TitleDesc
{
public string Title { get; set; }
public int Priority { get; set; }
public Attribute[] attributes { get; set; }
}

public class Attribute
{
public string Title { get; set; }
public string Value { get; set; }
public int Priority { get; set; }
}

然后用这段代码序列化

string jsonString = "[{'Title': 'OVERVIEW','Priority': 1,'attributes': [{    'Title': 'Type',    'Value': 'MacBook Pro',    'Priority': 1    },    {       'Title': 'Operating system',       'Value': 'OS X Mountain Lion',       'Priority': 2    },    {       'Title': 'Processor',       'Value': 'Intel Core i5 Processor (2.3 GHz, 3.3 GHz with TurboBoost, 6MB cache)',       'Priority': 3   },   {       'Title': 'Storage',       'Value': '500 GB HDDM 5400 rpm',       'Priority': 4   }]},{'Title': 'SPECIFICATION','Priority': 2,'attributes': [{    'Title': 'RAM',    'Value': '4 GB DDR3',    'Priority': 1    }]},{'Title': 'SCREEN','Priority': 3,'attributes': [{    'Title': 'Screen size',    'Value': '13',    'Priority': 1    }]}]";
var data = JsonConvert.DeserializeObject<TitleDesc[]>(jsonString);

希望这对您有所帮助。

关于c# - 将嵌套的 JSON 数据解析为 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28450415/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com