.Net Core IConfiguration use to process the file Json

A few days ago the company to spend Ctrip open source configuration center: Apollo

Then my colleagues gave me such a question, because before, when we are .NET Core comes appsetting.json, for compatibility with the code of the current methods used for configuration tools in search, you need to configure center key written in the form [parent: child nodes: the child node]

Q. I have no good way to existing configuration files are converted to this, or manually copy too strenuous.

So I thought of using IConfiguration to json operation code is as follows:

By IConfiguration to continue to get the next child node and then recursively return

DirectoryInfo root = new DirectoryInfo(path);
            FileInfo[] files = root.GetFiles();
            foreach (var file in files)
            {
                var builder = new ConfigurationBuilder().AddJsonFile(file.FullName);
                var config = builder.Build();
                var first_chilren = config.GetChildren();
                var key_value = Recursion(first_chilren, "", true);
                foreach (var item in key_value)
                {
                    if (key_value_result.Any(x => x.key == item.key))
                    {
                        continue;
                    }                           
                    key_value_result.Add(new DiffJson {
                        key=item.key,
                        value=item.value,
                        file_name=file.Name
                    });
                }
            }
 public static IEnumerable<Json> Recursion(IEnumerable<IConfigurationSection> section, string parent_key, bool is_first)
        {
            List<Json> result = new List<Json>();
            foreach (var item in section)
            {
                var chiilren = item.GetChildren();
                string currnet_key = "";
                if (is_first)
                {
                    currnet_key = $"{item.Key}";
                }
                else
                {
                    currnet_key = $"{parent_key}:{item.Key}";
                }

                if (chiilren.Any())
                {
                    result.AddRange(Recursion(chiilren, currnet_key, false));
                }
                if (!string.IsNullOrWhiteSpace(item.Value))
                {
                    result.Add(new Json
                    {
                        key = currnet_key,
                        value = item.Value
                    });
                }             
            }
            return result;
        }

And finally returns effect:

 

Guess you like

Origin www.cnblogs.com/Tassdar/p/11240776.html