从Windows phone的webservice中读取json文件
本文关键字:读取 json 文件 webservice Windows phone | 更新日期: 2023-09-27 17:49:21
我对Windows Phone应用程序非常陌生。我有一个JSON文件,我从以下URL获得。
http://www.krcgenk.be/mobile/json/request/news/
现在我希望标题显示在我的Windows Phone上的列表中。我有以下XAML:
<Grid>
<ListBox x:Name="News" Height="532">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="0,0,12,0" />
<TextBlock Text="{Binding Description}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
现在我需要知道如何将标题和描述放入列表中。经过一些谷歌工作,我发现我应该使用JSON.net框架。这给了我下面的代码:
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<News>>(r.EventArgs.Result);
PhoneList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://www.krcgenk.be/mobile/json/request/news/"));
我还创建了一个带有getter和setter的news类。但当我建立和运行。我得到以下错误:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into
type 'System.Collections.Generic.List`1[KrcGenk.Classes.News]' because the
type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3])
or change the deserialized type so that it is a normal .NET type (e.g. not
a primitive type like integer, not a collection type like an array or
List<T>) that can be deserialized from a JSON object. JsonObjectAttribute
can also be added to the type to force it to deserialize from a JSON object.
Path 'news', line 1, position 8.
希望有人能帮助我?
url返回一个对象(这就是错误消息所说的)。所以你不应该把它反序列化成一个列表。反序列化应该像这样:
var deserialized =
JsonConvert.DeserializeObject<NewsEntry>(r.EventArgs.Result);
NewsEntry应该包含一个新闻列表
class NewsEntry {
public List<News> News { get; set; }
public NewsEntry() {
News = new List<News>();
}
}
注意:我假设News类具有所有属性。也许你需要调整一下这个
看看这篇博文http://dotnetbyexample.blogspot.gr/2012/01/json-deserialization-with-jsonnet.html