Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update one or some property(ies) in JSON file with nested data whilst preserving structure?

My json file looks like this

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "Parameters": {
        "Delay": 1000
    }
}

I only want to change the "Delay" property. I can’t figure it out for the life of me. On YouTube they only show fairly linear examples and other goodies not related to my question. It’s a .net Core project and I’m not even sure whether I should install Newstonsoft.json (according to the mighty YouTube System.Text.Json is almost identical).

So if anyone could help me out, that would be great. I don’t even know what datastructure I am supposed to make for a structure like this. Again because the examples available mention the most simple structures only.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you need only several lines of code

using Newtonsoft.Json;

var path=@"C:\...";
var json = File.ReadAllText(path);

var jObj = JsonConvert.Parse(json);

jObj["Parameters"]["Delay"] = 2000;

json = jObj.ToString();

File.WriteAllText(path, json);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading