gpt4 book ai didi

c# - 将Json String反序列化为多种Object类型

转载 作者:太空狗 更新时间:2023-10-29 21:38:56 24 4
gpt4 key购买 nike

我有一个从 Web 服务获取的 Json 字符串;它有一个集合列表,每个集合代表一个对象,例如:

  [ // Root List
[ // First Collection : Team Object
{
"id": 1,
"team_name": "Equipe Saidi",
"is_active": true,
"last_localisation_date": "2015-05-06T13:33:15+02:00"
},
{
"id": 3,
"team_name": "Equipe Kamal",
"is_active": true,
"last_localisation_date": "2015-05-06T09:22:15+02:00"
}
],
[// Second Collection : user Object
{
"id": 1,
"login": "khalil",
"mobile_password": "####",
"first_name": "Abdelali",
"last_name": "KHALIL",
"email": "KHALIL@gmail.com",
"role": "DR",
"is_active": true,
"charge": false
},
{
"id": 2,
"login": "ilhami",
"mobile_password": "####",
"first_name": "Abdellah",
"last_name": "ILHAMI",
"email": "ILHAMI@gmail.com",
"role": "DR",
"is_active": true,
"charge": false
}
]
]

我的实际代码(当然不工作):

 public async Task TeamsAndMobileUsers()
{
string data = "";
IList<User> MobileUsersList = new List<User>();
IList<Team> TeamsList = new List<Team>();
try
{
data = await GetResponse(PATH + TEAMS_USERS_URL);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(data);
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(data);

// Inserting
await SetAchievedActions(TeamsList);

}
catch (Exception e) {
_errors.Add(e.Message);
}
}

我使用 Json.net 和 C#。我找不到解决方案,我读到我应该使用 JsonReader 并将其 SupportMultipleContent 属性设置为 true,但我不知道如何实现该解决方案。

最佳答案

正如@YeldarKurmangaliyev 所说,您的 json 有两个不同的对象,我认为您可以这样做:

var j = JArray.Parse(data);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());

关于c# - 将Json String反序列化为多种Object类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30593869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com