如何根据XAML / C#中的JSON文件内容自动创建集线器?我的JSON看起来像这样:
[
{
"Title": "All Things Go",
"Length": "4:53",
"Features": "N/A"
},
{
"Title": "I Lied",
"Length": "5:04",
"Features": "N/A"
}
]
然后我想为每个对象自动创建一个集线器,然后在那里添加信息。有人知道这是怎么回事吗?
答案 0 :(得分:2)
假设有一个名为" test.json"的JSON文件;包含您在上面显示并位于"资产"内的内容。项目中的文件夹。 " test.json"文件如下:
[
{
"Title": "All Things Go",
"Length": "4:53",
"Features": "N/A"
},
{
"Title": "I Lied",
"Length": "5:04",
"Features": "N/A"
}
]
现在我们将从这个JSON文件创建一个Hub控件。要做到这一点,首先需要从这个JSON文件逐个读取项目(我们可以在这里将其读入一个实体,我创建一个Hubcontrol
类),其次需要将这些项目设置为HubSection
的属性然后将HubSection
添加到Hub控件。所以示例代码如下:
XAML代码
<Page
...
mc:Ignorable="d" Loaded="Page_Loaded">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" x:Name="root">
</Grid>
</Page>
代码背后:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
StorageFile jsonfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/test.json"));
string jsonString = await FileIO.ReadTextAsync(jsonfile);
var Allhubs = JsonArray.Parse(jsonString);
//Read json file, and deserialization the json string to Hubcontrol class.
List<Hubcontrol> hubsources = new List<Hubcontrol>();
foreach (IJsonValue jsonValue in Allhubs)
{
if (jsonValue.ValueType == JsonValueType.Object)
{
JsonObject hubcontrolitem = jsonValue.GetObject();
hubsources.Add(new Hubcontrol()
{
Title = hubcontrolitem.GetNamedString("Title"),
Length = hubcontrolitem.GetNamedString("Length"),
Features = hubcontrolitem.GetNamedString("Features")
});
}
}
//Create a new hub control, add hubsections which title is got from json
Hub HubFromJson = new Hub();
foreach (Hubcontrol hubcontrolitem in hubsources)
{
HubSection sectionitem = new HubSection();
sectionitem.Header = hubcontrolitem.Title;
HubFromJson.Sections.Add(sectionitem);
}
root.Children.Add(HubFromJson);
}
}
public class Hubcontrol
{
public string Title { get; set; }
public string Length { get; set; }
public string Features { get; set; }
}
我上传了演示here。