我正在嘗試使用C#和Json.Net爲Windows Phone 7創建一個reddit應用程序(僅用於練習)。我正試圖將json轉換爲c#可以與其他一些東西一起工作的東西。我可以提取我想要的數據,但不知道我是否正在使用正確的方法。然後,一旦我有JSON數據,我不能將其轉換爲自定義對象。無論如何,我敢肯定在這段代碼中有很多東西是錯誤的,所以任何幫助理清標題的幫助都會很感激。將json轉換爲自定義對象數組
下面的代碼:
public partial class MainPage : PhoneApplicationPage
{
string json = "";
RootObject topic = new RootObject();
public MainPage()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
textBlock1.Text = "Retrieving...";
string url = @"http://www.reddit.com/r/all.json";
HttpWebRequest hWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
hWebRequest.Method = "GET";
hWebRequest.BeginGetResponse(Response_Completed, hWebRequest);
}
public void Response_Completed(IAsyncResult result)
{
HttpWebRequest request = (HttpWebRequest)result.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
json = streamReader.ReadToEnd();
topic = JsonConvert.DeserializeObject<RootObject>(json);
}
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//textBlock2.Text = topic.data2.title;
textBlock1.Text = "Done.";
});
這行告訴我,一個「新」的調用是必需的。
textBlock2.Text = topic.data2.title;
現在這部分給了我麻煩。我如何正確地實例化數據,data2和孩子?
public class MediaEmbed
{
}
public class Data2
{
public string domain { get; set; }
public MediaEmbed media_embed { get; set; }
public object levenshtein { get; set; }
public string subreddit { get; set; }
public string selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public bool saved { get; set; }
public string id { get; set; }
public bool clicked { get; set; }
public string title { get; set; }
public object media { get; set; }
public int score { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public string author_flair_css_class { get; set; }
public int downs { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public string author_flair_text { get; set; }
public string author { get; set; }
public double created_utc { get; set; }
public int num_comments { get; set; }
public int ups { get; set; }
//public override string ToString()
//{
// return title;
//}
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public Child[] children { get; set; }
public string after { get; set; }
public object before { get; set; }
}
public class RootObject
{
public RootObject()
{
}
public string kind { get; set; }
public Data data = new Data();
public Data2 data2 = new Data2();
public Child child = new Child();
}
}
你有一個堆棧跟蹤? – 2011-12-17 05:58:03
剛剛添加到我的文章。 – Wilcoholic 2011-12-17 07:50:59