Reputation: 489
I'm new to c# and having problems with the below giving InvalidCastException on the line Addresses address = (Addresses)serializer.ReadObject(e.Result);
:
namespace My_App
{
[DataContract]
public class Addresses
{
[DataMember(Name = "line1")]
public string line1
{
get;
set;
}
[DataMember(Name = "line2")]
public string line2
{
get;
set;
}
[DataMember(Name = "postcode")]
public string rpostcode
{
get;
set;
}
[DataMember(Name = "city")]
public string city
{
get;
set;
}
[DataMember(Name = "state")]
public string state
{
get;
set;
}
}
public partial class sim : PhoneApplicationPage
{
public sim()
{
InitializeComponent();
}
private void Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var webClient = new WebClient();
webClient.OpenReadCompleted += OnOpenReadCompleted;
webClient.OpenReadAsync(new Uri("http://www.myurl" UriKind.Absolute));
}
}
private void OnOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
var serializer = new DataContractJsonSerializer(typeof(Addresses));
Addresses address = (Addresses)serializer.ReadObject(e.Result);
}
}
}
JSON:
[
{
"@type": "accountAddress",
"line1": " 1",
"line2": "NORWICH ROAD",
"postcode": "NR1 1AU",
"city": "NORWICH",
"state": "NORFOLK"
},
{
"@type": "accountAddress",
"line1": " 2",
"line2": "NORWICH ROAD",
"postcode": "NR1 1AU",
"city": "NORWICH",
"state": "NORFOLK"
},
{
"@type": "accountAddress",
"line1": " 3",
"line2": "NORWICH ROAD",
"postcode": "NR1 1AU",
"city": "NORWICH",
"state": "NORFOLK"
}
]
I need this to be in a suitable format to use in a listpicker object. Any help would be greatly appreciated.
Upvotes: 0
Views: 253
Reputation: 5557
Problem here is, your JSON has a set of addresses and you are just trying to access only one Address. In other words, your serializer returns a List of Addresses but you are trying to convert it to a single Addresses object.
So change your code to something like this,
List<Addresses> addressList = (List<Addresses>)serializer.ReadObject(e.Result);
And eventually what you need is a list or a collection to bind it to the ListPicker.
Upvotes: 1