Load json section to Dictionary C# and preserver insertion order

208 Views Asked by At

Json file entry looks like this: settings.json

{
"MyJson": {
    "Machine": "machine",
    "Date": "date",
    "Time": "time",
    "Milli": "milli"
}
}

And I am using below code to convert this json to dictionary in C#

 public static Dictionary<string,string> myDict{  get; private set; }

 var configuration = new ConfigurationBuilder().AddJsonFile("settings.json", false, true).Build();
        myDict = configuration.GetSection("MyJson").Get<Dictionary<string, string>>();

This code is storing key based sorted entries in myDict. I want to maintain the insertion order in myDict. Is there are solution for this?

2

There are 2 best solutions below

10
Yusuf Karaman On
public static LinkedDictionary<string, string> myDict { get; private set; }
var configuration = new ConfigurationBuilder().AddJsonFile("settings.json", false, true).Build();

myDict = configuration.GetSection("MyJson").Get<LinkedDictionary<string,string();
1
Serge On

There is no any practical use in order maintaining. If you need it for some weird reason, add to each item an order number like this, for example

"MyJson": {
    "10 Machine": "machine",
    "20 Date": "date",
    "25 Time": "time",
    "30 Milli": "milli"
}

Dictionary<string,string> myDict = configuration.GetSection("MyJson")
                          .Get<Dictionary<string,string>>()
                          .ToDictionary(x => x.Key.Substring(3), x => x.Value);

output

{
"MyJson": {
    "Machine": "machine",
    "Date": "date",
    "Time": "time",
    "Milli": "milli"
}

another more complicated way is to load config file directly from disk and parse it

string path = Directory.GetCurrentDirectory(); 

string json = File.ReadAllText(Path.Combine(path, "settings.json"));

Dictionary<string,string> myDict = JObject.Parse(json)["MyJson"]
                                  .ToObject<Dictionary<string, string>>();