如何将 JSON 嵌套对象数组反序列化为 C# 对象

我被这个问题难住了,无法继续。我也不是很有经验,因此将不胜感激您的帮助。我正在使用返回以下数据的 API:


{"userdata":[{"IdCustomer":"4","IdShop_group":"1","IdShop":"2","IdGender":"1","IdDefault_group":"3","IdLang":"2","Company":null,"Firstname":"John","Lastname":"Doe","Email":"johndoe@email.com","NumpadPIN":"99999999","Birthday":"1991-12-24","Newsletter":"0","Optin":"0","Active":"1","Date_add":"2019-04-09 07:37:29","Date_upd":"2019-07-17 11:38:25"}]}

我使用“json2csharp”设置了以下课程


public class Userdata

{

    public string IdCustomer { get; set; }

    public string IdShop_group { get; set; }

    public string IdShop { get; set; }

    public string IdGender { get; set; }

    public string IdDefault_group { get; set; }

    public string IdLang { get; set; }

    public object Company { get; set; }

    public string Firstname { get; set; }

    public string Lastname { get; set; }

    public string Email { get; set; }

    public string Birthday { get; set; }

    public string Newsletter { get; set; }

    public string Optin { get; set; }

    public string Active { get; set; }

    public string Date_add { get; set; }

    public string Date_upd { get; set; }

}


    public class User

{

    public IList<Userdata> userdata { get; set; }

}

这是我提取数据的方法


//changed the url for this question

    var URL = "https://dummyvalue.com";


                    var request = new HttpRequestMessage();

                    request.RequestUri = new Uri(URL);

                    request.Method = HttpMethod.Get;

                    request.Headers.Add("Accept", "application/json");

                    var client = new HttpClient();

                    HttpResponseMessage response = await client.SendAsync(request);

                    }

我的问题是如何分配/使用已反序列化的值?我想访问作为类对象详细信息的值,例如。


var name = userObject.Firstname;

var surname = userObject.Lastname;

我读了很多书并尝试了不同的方法,但我一定错过了一些东西..


紫衣仙女
浏览 77回答 1
1回答

繁华开满天机

您需要使用 RootObjectvar response = JsonConvert.DeserializeObject<RootObject>(json);foreach(var userObject in response.userdata){&nbsp; &nbsp; //use here userObject.Firstname;}
打开App,查看更多内容
随时随地看视频慕课网APP