我正在尝试在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
}
},
转换为以下内容
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/"));
}
} }
答案 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);