我具有结构复杂的JSON,并希望将其转换为DataTable以填充DataGrid。以下代码仅适用于平面JSON结构。我需要通用的解决方案才能将任何复杂的JSON转换为WPF应用程序的DataTable。
void FillGridWithData()
{
//[
//{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ]
//},
//{ "name":"BMW", "models":[ "320", "X3", "X5" ]
//},
//{ "name":"Fiat", "models":[ "500", "Panda" ] }]
string json = " [\r\n { \"name\":\"Ford\", \"models\":[ \"Fiesta\", \"Focus\", \"Mustang\" ] },\r\n { \"name\":\"BMW\", \"models\":[ \"320\", \"X3\", \"X5\" ] },\r\n { \"name\":\"Fiat\", \"models\":[ \"500\", \"Panda\" ] }\r\n ]"
JArray jarray = JArray.Parse(json);
DataTable table = jarray.ToObject<DataTable>();
this.datagrid.DataContext = table.DefaultView;
}
这是输出: Models
如果可能的话,请回答我如何在不为每个json创建类的情况下做到这一点,因为我必须使用很多不同的json结构。
这是一些我需要在DataGrid中显示的json的示例:
{
"Example": [
{
"Num": 1,
"Category": "Poslano",
"Date": "2019-01-07T00:00:00",
"Object": {
"Value1": "Ante Blažević",
"Value2": "54984",
"Value3: "4968",
"Value4": "48968",
"Value5": "Something"
},
"ValueString": "dgfhdfg",
"Value45": "dfghdf"
},
{
"Num": 2,
"Category": "Poslano",
"Date": "2019-01-07T00:00:00",
"Object": {
"Value1": "Nikica Rašlić",
"Value2": "5498",
"Value3": "8749",
"Value4": "54696",
"Value5": "Something"
},
"ValueString": "Bla",
"Value45": "dfghdf"
}
]
}