如何在c#中直接从url的原始Json数据中加载数据
本文关键字:数据 原始 Json 加载 url | 更新日期: 2023-09-27 18:04:10
<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。我能够直接加载到listBox从原始Json数据从一个URL。我想为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);
}
}
简单方便的方法使用jsonorm从nuget和创建一个数据层从收到的json (http://json2csharp.com/)
为什么不从Datatable中加载呢?那会很简单的
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));