簡體   English   中英

將嵌套類從 json 反序列化為 c# 對象

[英]Deserialize nested classes from json into c# objects

我正在嘗試從這里反序列化 JSON 。 而且我不能使用來自 class Global 的 ie 屬性。

namespace CoVID2
{
    public class CovidStats
    {
        public string ID { get; set; }
        public string Message { get; set; }
        public class Global {
            public int NewConfirmed { get; set; }
            public int TotalConfirmed { get; set; }
            public int NewDeaths { get; set; }
            public int TotalDeaths { get; set; }
            public int NewRecovered { get; set; }
            public int TotalRecovered { get; set; }
            public string Date { get; set; }
        }
}
private void button1_Click(object sender, EventArgs e)
{
        using (WebClient client = new WebClient())
        {
            string s = client.DownloadString(url);
            CovidStats stat = JsonConvert.DeserializeObject<CovidStats>(s);
            MessageBox.Show(stat.Global.TotalConfirmed.ToString()); // This is the place, where i get an error
        }
    }

錯誤 CS0572“全局”:無法通過表達式引用類型; 嘗試 'CovidStats.Global' 代替 CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 活動錯誤 CS0120 非靜態字段、方法或屬性需要 object 引用。 .TotalConfirmed' CoVID2 C:\Users\Yan\source\repos\CoVID2\CoVID2\Form1.cs 64 活動

您可以使用https://json2csharp.com/輕松地將有效的 JSON 字符串轉換為 C# 類。

基於來自https://api.covid19api.com/summary 的 JSON我得到以下結果:

// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse); 
public class Global
{
    public int NewConfirmed { get; set; }
    public int TotalConfirmed { get; set; }
    public int NewDeaths { get; set; }
    public int TotalDeaths { get; set; }
    public int NewRecovered { get; set; }
    public int TotalRecovered { get; set; }
    public DateTime Date { get; set; }
}

public class Premium
{
}

public class Country
{
    public string ID { get; set; }
    public string Country { get; set; }
    public string CountryCode { get; set; }
    public string Slug { get; set; }
    public int NewConfirmed { get; set; }
    public int TotalConfirmed { get; set; }
    public int NewDeaths { get; set; }
    public int TotalDeaths { get; set; }
    public int NewRecovered { get; set; }
    public int TotalRecovered { get; set; }
    public DateTime Date { get; set; }
    public Premium Premium { get; set; }
}

public class Root
{
    public string ID { get; set; }
    public string Message { get; set; }
    public Global Global { get; set; }
    public List<Country> Countries { get; set; }
    public DateTime Date { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM