【问题标题】:read a json file from webservice in windows phone从 windows phone 中的 webservice 读取 json 文件
【发布时间】:2012-12-22 16:14:33
【问题描述】:

我对 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.

希望有人能帮助我吗?

【问题讨论】:

    标签: c# json windows-phone-7 data-binding


    【解决方案1】:

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

    【讨论】:

    • 我的班级呼叫新闻。我应该用 News 替换 NewsEntry 吗?
    • 您应该创建一个新类 NewsEntry,其中包含一个名为 News 的属性。返回的 json 传递一个对象(不是列表/数组),其中包含一个名为 news 的属性,该属性实际上是 News 的列表/数组。所以我提议的 NewsEntry 类提供了外部容器,如果你喜欢这样命名的话。
    • 好的,我做到了,但现在它给了我以下错误。错误 1 ​​无法将 lambda 表达式转换为类型“System.IObserver>”,因为它不是委托类型,并且 thisError 2 无法隐式转换类型“KrcGenk.Classes.NewsEntry”到“System.Collections.IEnumerable”。存在显式转换(您是否缺少演员表?)
    • 尝试改变PhoneList.ItemsSource = deserialized;到 PhoneList.ItemsSource = 反序列化.News;因为新闻包含列表
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多