I’m trying to parse a JSON file for a Windows Phone app, and my current code is:
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(RootObject));
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 songHistory = (station1)serializer.ReadObject(eargs.Result);
Button1.Content = songHistory.text;
}
};
var uri = new Uri("<JSONGOESHERE>");
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 RootObject
{
public station1 station1 { get; set; }
public station2 station2 { get; set; }
public station3 station3 { get; set; }
}
I require the same fetching of text for “station2” and “station3” later as well, which is why I’ve left them in.
Currently, what happens is I am getting the following error when I run this on the line
var songHistory = (station1)serializer.ReadObject(eargs.Result);
InvalidCastException was unhandled by user code
An exception of type ‘System.InvalidCastException’ occurred in APP.DLL but was not handled in user code
Unable to cast object of type ‘RootObject’ to type ‘station1’.
I had used the json2csharp generator to create the above so I’m not sure what’s wrong.
Any help would be awesome.
You created a serializer for the type
RootObject. So the output ofReadObjectis that type. Just cast it correctly (there is no generic overload forReadObject):