如何在导航到另一个页面时使用反序列化的对象?

时间:2014-08-03 19:12:26

标签: c# windows-phone-8 json-deserialization

所以基本上我有一个按钮。当我点击它时,必须发生两件事。

1)获取数据的Web请求

2)导航到另一页并填充数据

问题是当app导航到page2时,App.mydirectories会给出nullreferenceException ...

如何确保App.mydirectories不为空并在将数据填充到新页面之前等待。

private void Button_Click(object sender, RoutedEventArgs e)
        {
            makeEventwebRequest(number.Text,date.Text);


            NavigationService.Navigate(new Uri("/page2.xaml", UriKind.Relative));
        }

        public void makeEventwebRequest(string numb, string date)
        {

            string requesturi = string.Format(baseUri, numb, date);
            try
            {
                WebClient client = new WebClient();


                client.DownloadStringCompleted +=
                new DownloadStringCompletedEventHandler(directories_DownloadStringCallback);

                client.DownloadStringAsync(new Uri(requesturi));
            }
            catch (Exception e)
            {
            }

        }
        private void directories_DownloadStringCallback(object sender, DownloadStringCompletedEventArgs e)
        {


                    App.mydirectories = JsonConvert.DeserializeObject<directoriescs>(e.Result);



        }

1 个答案:

答案 0 :(得分:1)

发生此错误是因为执行WebRequest的代码是异步的。当您导航到page2.xaml时,您的数据尚未下载。

这是一个关于如何执行代码的示例:

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        await makeEventwebRequest(number.Text,date.Text);
        NavigationService.Navigate(new Uri("/page2.xaml", UriKind.Relative));
    }

    public async void makeEventwebRequest(string numb, string date)
    {
        string requesturi = string.Format(baseUri, numb, date);
        var request = (HttpWebRequest)WebRequest.Create(requesturi );
        var result = await GetHttpResponse(request);
        App.mydirectories = JsonConvert.DeserializeObject<directoriescs>(result);
    }

    // Method helper to Http async request
    public static async Task<String> GetHttpResponse(HttpWebRequest request)
    {
        String received = null;

        try
        {
            using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
            {
                using (var responseStream = response.GetResponseStream())
                {
                    using (var sr = new StreamReader(responseStream))
                    {

                        received = await sr.ReadToEndAsync();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        return received;
    }

你应该阅读一篇关于异步/等待方法的文章,例如http://msdn.microsoft.com/en-us/library/hh191443.aspx,这样你就可以更好地理解你的代码与我的不同之处。

基线是你在webrequest仍在进行时导航到page2,而在我上面发布的代码中,执行等待web请求完成,然后导航到page2。