使用Json Converter向Dictionary添加属性

时间:2017-12-28 18:21:15

标签: c# json dictionary json.net

我通过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();
    }
}

有没有办法让这项工作或我需要改变我的方法?

1 个答案:

答案 0 :(得分:1)

您根本不需要特殊转换器,只需删除NUnavailResReasonsMaps类并改为使用Dictionary<int, int>

public class VoiceIaqStats
{
    //snip
    public Dictionary<int, int> NUnavailResReasonsMap { get; set; }
    //snip
}

转换将开箱即用:

var result = JsonConvert.DeserializeObject<QueueStats>(json);