Search code examples
c#json.net-5lexicographic

System.Text.Json: Sort by key Hashtable?


I am serializing my object using a simple:

var options = new JsonSerializerOptions { WriteIndented = true, IncludeFields = true};
string jsonString = JsonSerializer.Serialize(obj, options);
File.WriteAllText("output.json", jsonString);

However my hierarchy contains a Hashtable. I'd like to have the Hashtable content be written in a consistent manner: always order by Keys (key is string in my case).

How can I do that in .NET 5 ?


My question is about Hashtable content and is no way related to ordering of class fields.


I cannot simply change the type of Hashtable to SortedDictionary since this would break all my existing BinaryFormatter serialized streams.


Solution

  • You could use a property as a pass-through:

        [JsonIgnore]
        public Hashtable MyHashtable { get; set; }
        
        [JsonPropertyName("MyHashtable")]
        public SortedDictionary<string, string> MyHashtableSorted 
        {
            get => new SortedDictionary<string, string>(
                         MyHashtable
                         .Cast<DictionaryEntry>()
                         .ToDictionary(x => (string)x.Key, x => (string)x.Value)
                    );
            set {
                MyHashtable = new Hashtable();
                foreach (var x in value)
                    MyHashtable.Add(x.Key, x.Value);
            }
        }
    

    Or just use a SortedDictionary as your property type to start with...