skip to Main Content

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

Answers


  1. 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();
    
    Login or Signup to reply.
  2. 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"
    }
    
    var myDict = configuration.GetSection("MyJson")
                              .Get<Dictionary<string,string>>()
                              .ToDictionary(x => x.Key.Substring(3), x => x.Value);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search