我試圖解析一個JSON文件,當有人點擊一個按鈕,從JSON數據替換按鈕的內容。解析JSON時的NullReferenceException
目前我遇到了數據保持空白的問題。代碼如下:
private void Button1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Button1.FontSize = 15;
Button1.Content = "Fetching...";
var client = new WebClient();
client.OpenReadCompleted +=
(s, eargs) =>
{
var serializer = new DataContractJsonSerializer(typeof(RadioRootObject));
if (eargs.Error != null)
{
if (eargs.Error.Message.Contains("NotFound"))
{
MessageBox.Show("Could not retrieve playlist", "Error", MessageBoxButton.OK);
Button1.Content = "Could not retrieve playlist";
}
else
{
MessageBox.Show("Could not retrieve playlist", "Error", MessageBoxButton.OK);
Button1.Content = "Could not retrieve playlist";
}
}
else
{
var root = (RadioRootObject)serializer.ReadObject(eargs.Result);
var songHistory = root.station3;
Button1.Content = songHistory.text;
}
};
var uri = new Uri("http://www.reignofcomputer.com/tmpsend/nowplaying.json");
client.OpenReadAsync(uri);
}
public class station1
{
public string station { get; set; }
public string title { get; set; }
public string artist { get; set; }
public string text { get; set; }
}
public class station2
{
public string station { get; set; }
public int listeners { get; set; }
public string title { get; set; }
public string artist { get; set; }
public string text { get; set; }
}
public class station3
{
public string station { get; set; }
public int listeners { get; set; }
public string title { get; set; }
public string artist { get; set; }
public string text { get; set; }
}
public class RadioRootObject
{
public station1 station1 { get; set; }
public station2 station2 { get; set; }
public station3 station3 { get; set; }
}
root
和songHistory
保持空,從而拋出一個NullReferenceException。
station1
和station2
在Button2_Tap
和Button3_Tap
使用,而不是在上面的代碼中,這類似於上面Button1_Tap
所示。
我被告知DataContractJsonSerializer無法將json對象的屬性「1」與RadioRootObject類的屬性station1匹配,但我不確定如何使它匹配。
我無法修改JSON本身的數據。有任何想法嗎?
布里爾巨無霸,這是做到了。非常感謝。 – ReignOfComputer