0

我是 c# 的新手,并且在下面给出 InvalidCastException 时遇到问题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"
    }
]

我需要它采用合适的格式才能在 listpicker 对象中使用。任何帮助将不胜感激。

4

1 回答 1

1

这里的问题是,您的 JSON 有一组地址,而您只是试图访问一个地址。换句话说,您的序列化程序返回一个地址列表,但您正试图将其转换为单个地址对象。

所以把你的代码改成这样,

List<Addresses> addressList = (List<Addresses>)serializer.ReadObject(e.Result);

最终,您需要一个列表或集合来将其绑定到 ListPicker。

于 2012-06-27T05:53:27.607 回答