简体   繁体   English

将 Json 数据加载到 WPF

[英]Loading Json data to WPF

I'm trying to load Json file into my wpf project but it's not working.. Can you help me please?我正在尝试将 Json 文件加载到我的 wpf 项目中,但它不起作用..你能帮我吗? I watched many videos and still didn't find the right solution看了很多视频还是没有找到合适的解决办法

After ruining program is throwin an exception "Error converting value "{" to type 'Test.MyLibrary', Path", line 3, position 1破坏程序后抛出异常“错误转换值“{”到类型'Test.MyLibrary',路径”,第3行,位置1

This is my Json file "test.json".这是我的 Json 文件“test.json”。

{
                    "Name" : "Apple",  

                    "ExpiryDate" : "May",

                    "Price" : 3.99

                    }

This is my class MyLibrary这是我的课程 MyLibrary

 class MyLibrary
{


        public string Name { get; set; }
        public string ExpiryDate { get; set; }
        public double Price { get; set; }

}

My C# code我的 C# 代码

public MainWindow()
    {

        string path = "test.json";
        String myStream= File.ReadAllText(path);
        InitializeComponent();


        try

        {

            MyLibrary myLibrary= JsonConvert.DeserializeObject<MyLibrary>(myStream.ToString());

            DataContext = myLibrary;

        }

        catch (Exception ex)

        {


            MessageBox.Show(ex.Message);

        }

And now i want to show Name in WPF label现在我想在 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>

What i'm doing wrong ?我在做什么错? Any ideas?有任何想法吗?

Do you have any error, exception?您有任何错误,异常吗? What is wrong?怎么了? Also you didn't write which library you use for JSON serialization(I assume it is Newtonsoft.Json).此外,您没有编写用于 JSON 序列化的库(我假设它是 Newtonsoft.Json)。

I tried your code but with one small change and works:我试过你的代码,但有一个小的改变,并且有效:

MyLibrary myLibrary = JsonConvert.DeserializeObject<MyLibrary>(@"{""Name"" : ""Apple"", ""ExpiryDate"" : ""May"", ""Price"" : 3.99}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM