WP7反序列化JSON

时间:2012-06-26 23:58:40

标签: json windows-phone-7 serialization

我是c#的新手,并且在下面的行Addresses address = (Addresses)serializer.ReadObject(e.Result);上给出了InvalidCastException时遇到了问题:

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对象中使用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

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

所以将你的代码改为这样的,

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

最终你需要的是一个列表或集合来将它绑定到ListPicker。