-1

我正在尝试在 WP7 上将 JSON api 反序列化为 c#。我需要帮助。我确定它很容易解决,但我不能只看到它。

JSON 数据如下所示。

{
"chartDate" : 1349564400, 
"retrieved" : 1349816722, 
"entries" : 
[
    {
        "position" : 1, 
        "previousPosition" : 0, 
        "noWeeks" : 1, 
        "artist" : "Rihanna", 
        "title" : "Diamonds", 
        "change" : 
        {
            "direction" : "none",
            "amount" : 0,
            "actual" : 0
        }
    }, 

使用http://json2csharp.com/转换为以下内容

    public class Change
  {
      public string direction { get; set; }
      public int amount { get; set; }
      public int actual { get; set; }
  }

  public class Entry
  {
      public int position { get; set; }
      public int previousPosition { get; set; }
      public int noWeeks { get; set; }
      public string artist { get; set; }
      public string title { get; set; }
      public Change change { get; set; }
  }

  public class RootObject
  {
      public int chartDate { get; set; }
      public int retrieved { get; set; }
      public List<Entry> entries { get; set; }
  }

在应用程序中,当我单击获取提要按钮时,我正在使用以下代码,但它返回错误无法将 JSON 对象反序列化为类型“System.Collections.Generic.List`1[Appname.RootObject

以下是我来自 Mainpage.cs 的 C#

using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using Newtonsoft.Json;

namespace JsonDemo
{
  public partial class MainPage : PhoneApplicationPage
  {
    // Constructor
    public MainPage()
    {
  InitializeComponent();
}

private void Load_Click(object sender, RoutedEventArgs e)
{
  var w = new SharpGIS.GZipWebClient();
  Observable.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
    .Subscribe(r =>
    {
        var deserialized = JsonConvert.DeserializeObject<List<RootObject>>(r.EventArgs.Result);
      PhoneList.ItemsSource = deserialized;
    });
  w.DownloadStringAsync(new Uri("http://apiurl.co.uk/labs/json/"));
}

} }

4

1 回答 1

2

如果r.EventArgs.Result返回有问题的(正确的)json,这应该有效:

var deserialized = JsonConvert.DeserializeObject<RootObject>(r.EventArgs.Result);

- 编辑 -

string json = @"{
    ""chartDate"": 1349564400,
    ""retrieved"": 1349816722,
    ""entries"": [{
        ""position"": 1,
        ""previousPosition"": 0,
        ""noWeeks"": 1,
        ""artist"": ""Rihanna"",
        ""title"": ""Diamonds"",
        ""change"": {
            ""direction"": ""none"",
            ""amount"": 0,
            ""actual"": 0
        }
    }]
    }";

var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
于 2012-10-09T21:26:28.023 回答