繁体   English   中英

将 Json 反序列化为 C# 类返回 null

[英]Deserializing Json to C# class returns null

我有这段代码可以调用返回 Json 的 PHP

string str = "https://url/file.php";
        string[] cID = new string[] { "act=qwjFpPXuGexZBHDJEreZrAUH&CID=", "&username=", Username, "&password=", Password };
        string str1 = string.Concat(cID);
        using (WebClient webClient = new WebClient())
        {
            webClient.Proxy = null;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            string str2 = webClient.UploadString(str, str1).Replace("\r", "").Replace("\n", "").Trim();

            JsonConvert.DeserializeObject<List<Information>>(str2);

str2 返回这个 Json

[{"username":"xxxxxx","email":"xxxxxxxx@xxxxx.com","plan":"0","activationdate":"","terminationdate":""}]

这就是我想要的,但是当我尝试将它传递给这个类时,它什么也不发送:

public class Information
{
    
    public string ID { get; set; }
    public string username { get; set; }
    public string email { get; set; }
    public string plan { get; set; }
    public string activationdate { get; set; }
    public string terminationdate { get; set; }

    public Information()
    {
        
    }
}

如果我尝试这样做

label11.Text = Information.username;

我在标签上得到“null”并出现此错误:非静态字段、方法或属性需要对象引用。

我做错了什么,如何正确反序列化到类以便能够将类的内容显示到标签中?。

您必须将值分配给变量并使用 variables 属性将值分配给您的标签。

List<Information> myVariable = JsonConvert.DeserializeObject<List<Information>>(str2);

label11.Text = myVariable[0].username;

如果不先创建类的实例,就不能简单地访问类的属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM