为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
紫衣仙女 2023-07-09 16:17:21
我被这个问题难住了,无法继续。我也不是很有经验,因此将不胜感激您的帮助。我正在使用返回以下数据的 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;我读了很多书并尝试了不同的方法,但我一定错过了一些东西..
查看完整描述

1 回答

?
繁华开满天机

TA贡献1816条经验 获得超4个赞

您需要使用 RootObject


var response = JsonConvert.DeserializeObject<RootObject>(json);

foreach(var userObject in response.userdata)

{

    //use here userObject.Firstname;

}



查看完整回答
反对 回复 2023-07-09
  • 1 回答
  • 0 关注
  • 76 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信