每秒从json Web服务获取数据

时间:2013-08-22 14:16:33

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

我为Windows Phone项目创建了一个json Web服务。我需要每秒从Web服务中恢复数据,我使用带线程的DispatcherTimer系统

private void client_DownloadInfoConf(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            //some code
            DispatcherTimer TradeThread = new DispatcherTimer();
            TradeThread.Interval = TimeSpan.FromMilliseconds(1000);
            TradeThread.Tick += new EventHandler(dispatcherTimer_Tick);
            TradeThread.Start();

        }
        else
            MessageBox.Show("Error : " + e.Error);
    }
    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {
        WebClient client_quest = new WebClient();


        client_quest.DownloadStringAsync(new Uri("url" + info_conf.id));
        client_quest.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadQuestConf); 
    }
    private void client_DownloadQuestConf(object sender, DownloadStringCompletedEventArgs e)
    {
        if (e.Error == null)
        {
            string text = e.Result;
            QuestConf resultat = JsonConvert.DeserializeObject<QuestConf>(e.Result);
            string sub = texte.Substring(0, 5);
            TextBlock text_quest = new TextBlock();
            foreach (var cust in resultat)
            {

                //The problem is here, i can't retrieve data from the object
            }
        }
        else
            MessageBox.Show("Error" + e.Error);
    }

这里的问题是,如果我尝试从“var cust”获取数据,则会发生错误,我无法从对象中提取数据...

用于提取json Web服务数据的类

 public class Question
    {
        public string id { get; set; }
        public string category { get; set; }
        public string name { get; set; }
        public string value { get; set; }
    }

    public class Answer
    {
        public string id { get; set; }
        public string label { get; set; }
    }

    public class QuestConf:List<object>
    {
        public Question question { get; set; }
        public List<Answer> answers { get; set; }
    }

提前感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果要从Web服务获取数据并想要反序列化到对象,我相信您应该将[DataContract]和[DataMember]属性添加到您的类和属性中。对从Web服务检索的每个对象都尝试这样:

[DataContract]
public class QuestConf:List<object>
{
    [DataMember]
    public Question question { get; set; }
    [DataMember]
    public List<Answer> answers { get; set; }
}