【发布时间】:2018-06-09 07:04:58
【问题描述】:
我正在通过 JArray.Parse() 将一些 JSON 端点反序列化为 C# 对象,并且遇到了一个我不知道如何处理的架构。下面的 nUnavailResReasonsMap 对象具有动态数量的名称/值对;所有名称值都是整数:
{
"id": "Customer Service",
"operation": "UPDATE",
"VoiceIAQStats": {
"id": 139,
"esdId": 139,
...
"nUnavailResources": 2,
"nUnavailResReasonsMap": {
"4": 1,
"9": 1
},
"nWorkResources": 0,
"nSelectedResources": 0,
...
"nSLAPercentageHighThreshold": 0
}
}
这是我的 C# 对象:
//Root Level
public class QueueStats
{
public string Id { get; set; }
public string Operation { get; set; }
public VoiceIaqStats VoiceIaqStats { get ; set ; }
}
public class VoiceIaqStats
{
public int Id { get; set; }
public int EsdId { get; set; }
...
public int NUnavailResources { get; set; }
public NUnavailResReasonsMaps NUnavailResReasonsMap { get ; set ; }
public int NWorkResources { get; set; }
public int NSelectedResources { get; set; }
...
public int NSlaPercentageHighThreshold { get; set; }
}
[JsonConverter( typeof( QueueStatsConverter))]
public class NUnavailResReasonsMaps
{
public Dictionary<string ,int > NUnavailResReasonsMap { get; set; }
}
根据另一篇 SO 帖子,我设置了下面的 Json 转换器,该转换器正在被调用,但我不确定如何将值放入上面定义的字典中。
public class QueueStatsConverter : JsonConverter
{
public override bool CanConvert( Type objectType)
{
return objectType.IsClass;
}
public override bool CanWrite => false;
public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var instance = objectType.GetConstructor(Type .EmptyTypes)?.Invoke(null);
var props = objectType.GetProperties();
var jo = JObject.Load(reader);
foreach ( var jp in jo.Properties())
{
//I can see the properties, but how do I add them to my existing dictionary?
}
return instance;
}
public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
有没有办法让这项工作发挥作用,还是我需要改变我的方法?
【问题讨论】:
-
有没有理由让 NUnavailResReasonsMaps 甚至需要存在?看来您可以将字典本身放入 VoiceIaqStats
-
将字典直接放在
VoiceIaqStats中,如下所示:public class VoiceIaqStats { public Dictionary<string ,int > NUnavailResReasonsMap { get ; set ; } ... }应该可以工作。请参阅Create a strongly typed c# object from json object with ID as the name 或How can I parse a JSON string that would cause illegal C# identifiers?。 -
是的 - 做到了,谢谢你的帮助。
标签: c# json dictionary json.net