C# 将Json数据加载到WPF
我正在尝试将Json文件加载到我的wpf项目中,但它不起作用。。 你能帮我吗?我看了很多视频,仍然没有找到正确的解决方案 破坏程序后,会出现异常“将值“{”转换为类型“Test.MyLibrary”,Path”,第3行,位置1 这是我的Json文件“test.Json” 这是我的班级图书馆C# 将Json数据加载到WPF,c#,json,wpf,binding,C#,Json,Wpf,Binding,我正在尝试将Json文件加载到我的wpf项目中,但它不起作用。。 你能帮我吗?我看了很多视频,仍然没有找到正确的解决方案 破坏程序后,会出现异常“将值“{”转换为类型“Test.MyLibrary”,Path”,第3行,位置1 这是我的Json文件“test.Json” 这是我的班级图书馆 class MyLibrary { public string Name { get; set; } public string ExpiryDate { get; se
class MyLibrary
{
public string Name { get; set; }
public string ExpiryDate { get; set; }
public double Price { get; set; }
}
我的C代码
public主窗口()
{
string path=“test.json”;
字符串myStream=File.ReadAllText(路径);
初始化组件();
尝试
{
MyLibrary MyLibrary=JsonConvert.DeserializeObject(myStream.ToString());
DataContext=myLibrary;
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message);
}
现在我想在WPF标签中显示名称
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MyLibrary/>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBox x:Name="firstLabel" Text="{Binding Path=Name}"></TextBox>
<Label Content="{Binding Path=Price}"></Label>
</StackPanel>
</Grid>
我做错了什么?有什么想法吗?你有什么错误吗,异常?有什么问题吗?而且你没有编写用于JSON序列化的库(我假设它是Newtonsoft.JSON) 我尝试了你的代码,但只做了一点小改动,效果很好:
MyLibrary myLibrary = JsonConvert.DeserializeObject<MyLibrary>(@"{""Name"" : ""Apple"", ""ExpiryDate"" : ""May"", ""Price"" : 3.99}");
MyLibrary MyLibrary=JsonConvert.DeserializeObject(@“{”名称“:”苹果“,”到期日“:”五月“,”价格“:3.99}”);
请注意myStream.ToString()
毫无意义。尽管名称不同,myStream
已经是一个字符串。除此之外,您肯定没有将JSON文件放在正确的位置。file.ReadAllText(“test.JSON”)
需要应用程序当前目录中的文件。我的项目文件夹Debug中有此文件。我可以在程序中看到此文件。然后请写一个更精确的问题描述。“它不起作用”并不能告诉我们太多。在破坏程序后,我已经在底部回答了“错误转换值”异常{“键入'Test.MyLibrary',Path”,第3行,位置1问题描述应该是问题正文的一部分,而不是对某个答案的注释,因此请编辑您的问题。除此之外,您的代码在JSON文件中对我来说很好。您是对的。我正在使用(Newtonsoft.JSON)。关键是当我声明我的“JSON文件”时“在程序内的字符串中,然后一切正常。但我的目标是通过从文件加载来实现。破坏程序后,会出现异常“将值“{”转换为类型“Test.MyLibrary”,Path”,第3行,位置1
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Test"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<local:MyLibrary/>
</Window.DataContext>
<Grid>
<StackPanel>
<TextBox x:Name="firstLabel" Text="{Binding Path=Name}"></TextBox>
<Label Content="{Binding Path=Price}"></Label>
</StackPanel>
</Grid>
MyLibrary myLibrary = JsonConvert.DeserializeObject<MyLibrary>(@"{""Name"" : ""Apple"", ""ExpiryDate"" : ""May"", ""Price"" : 3.99}");