【问题标题】:Deserializing Json to C# class returns null将 Json 反序列化为 C# 类返回 null
【发布时间】:2020-11-22 01:54:32
【问题描述】:

我有这段代码调用一个返回 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

[{"用户名":"xxxxxx","email":"xxxxxxx@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”并且出现以下错误:非静态字段、方法或属性需要对象引用。

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

【问题讨论】:

    标签: c# json serialization


    【解决方案1】:

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

    List<Information> myVariable = JsonConvert.DeserializeObject<List<Information>>(str2);
    
    label11.Text = myVariable[0].username;
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多