C#JSON反序列化为字符串的结果

本文关键字:结果 字符串 反序列化 C#JSON | 更新日期: 2023-09-27 17:49:39

我使用json2csharp生成函数和类,但我是个新手。我想要的是使用JSON数组中的数据并将其显示在文本框中。

这是代码:

 public class Sent_SMS
    {
        public string status { get; set; }
        public string error { get; set; }
        public string smslog_id { get; set; }
        public string queue { get; set; }
        public string to { get; set; }
    }
    public class RootObject
    {
        public List<Sent_SMS> data { get; set; }
        public object error_string { get; set; }
        public int timestamp { get; set; }
    }
    public void doSendSMS()
    {
        /* API URLs */
        APIURL_Send = "http://ipadressofgateway/playsms/index.php?app=ws&op=pv&h=" + apikey + "&u=" + username + "&to=" + receiver_number + "&msg=" + message; // Sending Message

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(APIURL_Send);
            var SMS_Log = JsonConvert.DeserializeObject<RootObject>(json);
            richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data.to + "Status is:" + SMS_Log.data.status;
        }
        }

但当然。。这不起作用,因为"SMS_Log.data.to"answers"SMS_Logg.data.status"不正确。如何正确地做到这一点?

问候

C#JSON反序列化为字符串的结果

如果您确定响应中总是只有一条SMS,那么将代码更改为:

richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data[0].to + "Status is:" + SMS_Log.data[0].status;

否则,我会选择这样的解决方案:

var text = "";
foreach (var sms in SMS_Log.data) {
    text += "SMS has been sent to:" + sms.to + "Status is:" + sms.status + "'n";
}
richTextBox3.Text = text;

SMS_Log.data是Sent_SMS实例的列表,因此您必须遍历该列表才能获得每条消息的数据。

for(int i=0;i<SMS_Log.data.Count();i++)
{
     richTextBox3.Text = "SMS has been sent to:" + SMS_Log.data[i].to + "Status     is:" + SMS_Log.data[i].status;
}

尽管这只会将最后一个元素设置为TextBlock文本。建议您将这些添加到新列表中,并将此列表设置为GridViewListView

的源