How can I serialize/deserialize a dictionary with custom keys using Json.Net?

后端 未结 3 726
误落风尘
误落风尘 2020-11-28 13:15

I have the following class, that I use as a key in a dictionary:

    public class MyClass
    {
        private readonly string _property;

        public My         


        
3条回答
  •  情深已故
    2020-11-28 13:43

    Simpler, full solution, using a custom JsonConverter

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public class CustomDictionaryConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType) => objectType == typeof(Dictionary);
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            => serializer.Serialize(writer, ((Dictionary)value).ToList());
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            => serializer.Deserialize[]>(reader).ToDictionary(kv => kv.Key, kv => kv.Value);
    }
    

    Usage:

    [JsonConverter(typeof(CustomDictionaryConverter))]
    public Dictionary MyDictionary;
    

提交回复
热议问题