We are using these subsections to generate excel, and we want the list of sub-sections as it is stored in json file but GetSection("XPaths").GetChildren() is always returning sorted list of sub sections.
I am not able to understand why?
Here I want these Xpaths as it is stored in json file but I am always getting sorted data.
JSON: Here I shared only 4 values of XPath, in real it has more than 1000.
{
"XPaths": {
"CITY": "USER/@CITY",
"STATE": "USER/@STATE",
"COUNTRY": "USER/@COUNTRY",
"GENDER": "USER/@GENDER"
}
}
Code:
public static Dictionary<string, string?> GetXpaths(string form)
{
var xPaths = new Dictionary<string, string?>();
try
{
form = !File.Exists($"{form}.json") ? ($"{(int)FormToGetXpaths.Default}") : form;
var xPathbuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile($"{form}.json", optional: true, reloadOnChange: true);
var _xpathconfiguration = xPathbuilder.Build();
xPaths = _xpathconfiguration.GetSection("XPaths")
.GetChildren()
.ToList()
.ToDictionary(x => x.Key, x => x.Value);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to get XPaths for {form}n{ex.Message}");
}
return xPaths;
}
2
Answers
RFC7159 explicitly states that
So you can’t rely on the order being preserved. Some JSON serialization libraries might preserve it, some not, some others might have settings to control the sorting behavior, but in general, if you want your sections ordered in a specific way, you’ll have to add a sequence variable to each of them and then order them by that variable.
Alternatively, you may consider turning your object with keys into an array of objects – the order in arrays is preserved according to the standard.
Why you don’t try this instead of building config