当有人单击按钮时,我正在尝试解析 JSON 文件,该按钮将按钮的内容替换为来自 JSON 的数据。
目前我面临一个数据保持为空的问题。代码如下:
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
andstation2
用在Button2_Tap
andButton3_Tap
中,上面代码中没有显示,与上面类似Button1_Tap
。
我被告知 DataContractJsonSerializer 无法将 json 对象中的属性“1”与 RadioRootObject 类上的属性 station1 匹配,但我不确定如何让它匹配。
我无法更改 JSON 本身的数据。有任何想法吗?