在wp7上反序列化JSON列表

时间:2012-10-09 21:11:35

标签: c# json windows-phone-7 json.net

我正在尝试在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对象Deserilize为类型“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/"));
}

} }

1 个答案:

答案 0 :(得分: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);