如何直接从C#中的url原始Json数据加载dataGrid中的数据?

时间:2016-08-27 08:26:15

标签: c# json wpf datagrid

<ListView x:Name="listView" Height="150" Canvas.Left="10" Canvas.Top="60" Width="402">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Product ID" DisplayMemberBinding="{Binding productId}"/>
            <GridViewColumn Header="Product Name" DisplayMemberBinding="{Binding productName}"/>
            <GridViewColumn Header="Unit Price" DisplayMemberBinding="{Binding unitPrice}"/>
            <GridViewColumn Header="Units in stock" DisplayMemberBinding="{Binding unitsInStock}"/>
            <GridViewColumn Header="Reorder Level" DisplayMemberBinding="{Binding reorderLevel}"/>

        </GridView>
    </ListView.View>
</ListView>

<DataGrid x:Name="dataGrid" Canvas.Left="10" Canvas.Top="215" AutoGenerateColumns="False" Height="178" Width="402"
    HorizontalAlignment="Stretch" 
      VerticalAlignment="Stretch" 
      ItemsSource="{Binding Items}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="productId" Binding="{Binding Path=productId}"/>
        <DataGridTextColumn Header="productName" Binding="{Binding Path=productName}"/>
        <DataGridTextColumn Header="unitPrice" Binding="{Binding Path=unitPrice}"/>
        <DataGridTextColumn Header="unitsInStock" Binding="{Binding Path=unitsInStock}"/>
        <DataGridTextColumn Header="reorderLevel" Binding="{Binding Path=reorderLevel}"/>
    </DataGrid.Columns>
</DataGrid>

上面是两个WPF控件,listBox和dataGrid。我能够从URL中的原始Json数据直接加载到listBox中。我想为dataGrid做同样的事情。我想从原始Json数据加载数据到dataGrid。请帮忙。

产品类包含5个属性。

后端::

private void TestConnection(object sender, RoutedEventArgs e)
    {
        string url = "http://192.168.167.1:8080/StudentOnlineRetailerWeb/rest/product";
        WebClient client = new WebClient();
        string reply = client.DownloadString(url);
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Product>));
        listView.Items.Clear();
        List<Product> product;

        product = (List<Product>)serializer.ReadObject(client.OpenRead(url));
        foreach (Product temp in product)
        {
            listView.Items.Add(temp);
        }


    }

2 个答案:

答案 0 :(得分:0)

简单易用的方法从nuget使用jsonorm并通过(http://json2csharp.com/

从收到的json创建数据层

答案 1 :(得分:0)

为什么不从数据表加载,这很容易

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));