如何将JSON结果添加到标签?

时间:2016-03-04 17:25:19

标签: c# json winforms

我在C#Windows窗体应用程序上从JSON请求中检索答案时遇到问题。我的代码如下所示:

FormLoad

try
        { 
            var url = "http://webpage.com/dir/sub/folder/app/app.json";
            var json = new WebClient().DownloadString(url);

            Printer[] toners = JsonConvert.DeserializeObject<Printer[]>(json);


            foreach (var j in toners)
            {
                lblOpt.Text = j.opt;
                lblStatus.Text = j.status;
                lblRemaining.Text = j.remaining;
                lblCnt.Text = j.cnt;
                lblCapa.Text = j.capa;
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

我也有这个方法:

class Printer
    {
        public string opt { get; set; }
        public string status { get; set; }
        public string remaining { get; set; }
        public string cnt { get; set; }
        public string capa { get; set; } 
    }

但是当Form加载时,我得到了以下内容:

JSon Error

这是我从浏览器中的JSON得到的答案:

toner_black: {
    opt: 1,
    status: 0,
    remaining: 23,
    cnt: 3488,
    capa: 5000,
    id: "CK670EXP",
    serial: "CRUM-15050630450"
}

1 个答案:

答案 0 :(得分:1)

这里有几个问题。

1)当浏览器返回单个对象时,您期待数组。

Printer[] toners = JsonConvert.DeserializeObject<Printer[]>(json);

变为

var toner = JsonConvert.DeserializeObject<Printer>(json);

2)打印机属性隐藏在toner_black属性中。所以你还需要另一个课程:

public class PrinterWrapper {
  public Printer toner_black { get; set; }
}

3)您的Printer课程应为public - public class Printer { ... }

最终摘录如下:

var toner = JsonConvert.DeserializeObject<PrinterWrapper>(json).toner_black;
lblOpt.Text = toner.opt;
lblStatus.Text = toner.status;
lblRemaining.Text = toner.remaining;
lblCnt.Text = toner.cnt;
lblCapa.Text = toner.capa;