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.
CodePudding user response:
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...
CodePudding user response:
microsoft gives this advice to order as you want your object properties
using System.Text.Json;
using System.Text.Json.Serialization;
namespace PropertyOrder
{
public class WeatherForecast
{
[JsonPropertyOrder(-5)]
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
[JsonPropertyOrder(-2)]
public int TemperatureF { get; set; }
[JsonPropertyOrder(5)]
public string? Summary { get; set; }
[JsonPropertyOrder(2)]
public int WindSpeed { get; set; }
}
public class Program
{
public static void Main()
{
var weatherForecast = new WeatherForecast
{
Date = DateTime.Parse("2019-08-01"),
TemperatureC = 25,
TemperatureF = 25,
Summary = "Hot",
WindSpeed = 10
};
var options = new JsonSerializerOptions { WriteIndented = true };
string jsonString = JsonSerializer.Serialize(weatherForecast, options);
Console.WriteLine(jsonString);
}
}
}
// output:
//{
// "Date": "2019-08-01T00:00:00",
// "TemperatureF": 25,
// "TemperatureC": 25,
// "WindSpeed": 10,
// "Summary": "Hot"
//}