如何在C#中将没有名称的JSON数组转换为类

dauxcl2d  于 2023-11-20  发布在  C#
关注(0)|答案(2)|浏览(158)

我需要使用Newtonsoft.Json将JSON数组转换为C#类,但我不知道如何做到这一点。
我已经试过用

  1. public LeagueInfo[] leagueinfo { get; set; }

字符串

  1. public List<LeagueInfo> leagueinfo { get; set; }


我现在拥有的是:

  1. public class League
  2. {
  3. public LeagueInfo[] leagueinfo { get; set; }
  4. }
  5. public class LeagueInfo
  6. {
  7. public string queueType { get; set; }
  8. public string summonerName { get; set; }
  9. public bool hotStreak { get; set; }
  10. public int wins { get; set; }
  11. public bool veteran { get; set; }
  12. public int losses { get; set; }
  13. public string rank { get; set; }
  14. public string tier { get; set; }
  15. public bool inactive { get; set; }
  16. public bool freshBlood { get; set; }
  17. public string leagueId { get; set; }
  18. public string summonerId { get; set; }
  19. public int leaguePoints { get; set; }
  20. }
  1. league = JsonConvert.DeserializeObject<League>(data);

的字符串
当我尝试这样做时,我得到了这个错误:

  1. Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'League' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
  2. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
  3. Path '', line 1, position 1.'


我的JSON字符串

  1. [
  2. {
  3. "queueType": "RANKED_SOLO_5x5",
  4. "summonerName": "R2FTW",
  5. "hotStreak": false,
  6. "wins": 76,
  7. "veteran": true,
  8. "losses": 97,
  9. "rank": "II",
  10. "tier": "BRONZE",
  11. "inactive": false,
  12. "freshBlood": false,
  13. "leagueId": "2a74bbd0-20ba-11e9-9c10-d4ae52a70a5a",
  14. "summonerId": "n9Sw-4lZHg5Cd2oeMxe8dj9WGv1XQS3GZEMPX1VZHgVH5w",
  15. "leaguePoints": 75
  16. },
  17. {
  18. "queueType": "RANKED_FLEX_SR",
  19. "summonerName": "R2FTW",
  20. "hotStreak": false,
  21. "wins": 0,
  22. "veteran": false,
  23. "losses": 12,
  24. "rank": "IV",
  25. "tier": "IRON",
  26. "inactive": false,
  27. "freshBlood": false,
  28. "leagueId": "b75d4e60-2234-11e9-a815-d4ae527982aa",
  29. "summonerId": "n9Sw-4lZHg5Cd2oeMxe8dj9WGv1XQS3GZEMPX1VZHgVH5w",
  30. "leaguePoints": 0
  31. }
  32. ]


我该怎么做?

3okqufwl

3okqufwl1#

试试这个:

  1. League league = new League()
  2. {
  3. leagueinfo = JsonConvert.DeserializeObject<LeagueInfo[]>(data)
  4. };

字符串

yb3bgrhw

yb3bgrhw2#

问题是JSON解析器需要一个名称。我通过如下方式将名称添加到输出中来完成我的工作:

  1. var league = JsonConvert.DeserializeObject<'League>("{ leagueinfo: " + data + " }");

字符串
当然,这是一个有点黑客,但如果你没有收到更好的格式化数据,这可能是解决方案。

相关问题