![](/img/trans.png)
[英]Deserializing JSON to a C# class returns 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.