将Json嵌套到具有可变键名称的对象类中

  • 本文关键字:对象 嵌套 Json c# json nested
  • 更新时间 :
  • 英文 :


请帮它伤透我的脑筋。

Newtonsoft。Json。JsonSerializationException:"无法将当前JSON对象(例如{"name"反序列化为类型"System。集合。通用的列出"1[ExaAsset+UsersInInList]",因为该类型需要JSON数组(例如[1,2,3](才能正确反序列化。要修复此错误,请将JSON更改为JSON数组(例如[1,2,3](,或者更改反序列化类型,使其成为正常类型。NET类型(例如,不是像integer这样的基元类型,也不是像数组或List这样的集合类型(,可以从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);

UsersInInList的第一个键是用户名,而不是";用户";等等,所以我无法将其序列化为每个API响应的不同用户名。。。有什么想法吗?

您似乎需要将属性UsersInBinList更改为stringUsersInBinListDictionary,而不是UsersInBinList:的列表

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

我有两个观察结果:

  1. 我认为JSON包会给您带来问题,因为您正试图将JSON对象反序列化为JSON数组

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

最新更新