-1

我对 Windows Phone 应用程序非常陌生。我有一个从以下 URL 获得的 JSON 文件。

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 的新闻类。但是当我构建和运行时。我收到以下错误。

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.

希望有人能帮助我吗?

4

2 回答 2

0

看看这篇博文http://dotnetbyexample.blogspot.gr/2012/01/json-deserialization-with-jsonnet.html

于 2012-12-22T16:24:16.907 回答
0

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 类具有所有属性。也许你需要调整这个。

于 2012-12-22T16:24:28.430 回答