【问题标题】:Nested Json into Object Class with Variable Key names将 Json 嵌套到具有变量键名的对象类中
【发布时间】:2021-07-22 03:17:49
【问题描述】:

请帮助它打破我的大脑。

Newtonsoft.Json.JsonSerializationException: '无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[ExaAsset+UsersInBinList]' 因为该类型需要正确反序列化的 JSON 数组(例如 [1,2,3])。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径 'topUsers.usersInBinList['dwm-2 (xxxx-xxx-10)'].username',第 1 行,位置 855。'

"usersInBinList": {
        
        
        "dwm-2": {
            "username": "dwm-2",
            "fullName": "Service Account",
            "riskScore": 4.82
        }}


        public class UsersInBinList
        {
            public string username { get; set; }
            public string fullName { get; set; }
            public string photo { get; set; }
            public string title { get; set; }
            public double riskScore { get; set; }
        }

        public class TopUsers
        {
            public string key { get; set; }
            public string modelName { get; set; }
            public string groupingFeatureValue { get; set; }
            public string histSpan { get; set; }
            public string histogramDate { get; set; }
            public string histClassName { get; set; }
            public double confidenceFactor { get; set; }
            public int totalBinCount { get; set; }
            public int totalCount { get; set; }
            public long lastUpdate { get; set; }
            public Hist hist { get; set; }
            public Dictionary<string, List<UsersInBinList>> UsersInBinList { get; set; }
            public PeerGroupsInBinList peerGroupsInBinList { get; set; }
            public bool disabled { get; set; }
        }

asset = JsonConvert.DeserializeObject<ExaAsset>(APIresponse);

UsersInBinList 的第一个键是用户名而不是“用户”等,因此我无法将其序列化为每个 API 响应的不同用户名...有什么想法吗?

【问题讨论】:

标签: c# json nested


【解决方案1】:

看来您需要将stringUsersInBinList 的属性UsersInBinList 更改为Dictionary,而不是UsersInBinList 的列表:

 public Dictionary<string, UsersInBinList> UsersInBinList { get; set; }

【讨论】:

  • 你确实是个传奇。这正是我做错的。现在是一种享受,谢谢。
  • @Mac 很乐意提供帮助!
  • asset.topUsers.UsersInBinList[0].fullName
  • @Mac 您可以使用Values property of Dictionary 来获取所有值。
【解决方案2】:

我有 2 条意见供您参考:

  1. 我相信 JSON 包会给您带来问题,因为您正试图将 JSON object 反序列化为 JSON array

  2. 如果您的 JSON 中的属性名称不能很好地映射到您在 C# 中指定的名称,那么您可以使用 JsonPropertyAttribute 向 Newtonsoft JSON 库 https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm 表示这一点

【讨论】:

  • 是的,我试图编辑的东西很糟糕。下次我会说清楚谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多