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

Edit JSON file values without overwriting it in c#

I have this code and i want to edit json value but when i use something like this code another values goes "null" and i don’t want overwrite it i need to edit json value.

class cfg
{
        static void Main(string[] args)
        {
            generate_def();
            editvalues();
        }

        public static string defaultvalue = "off";

        public class Data
        {
            public string value { get; set; }
            public string value2 { get; set; }
        }

        public static void generate_def()
        {
            List<Data> _data = new List<Data>();
            _data.Add(new Data()
            {
                value = defaultvalue,
                value2 = defaultvalue,
            });

            string json = JsonConvert.SerializeObject(_data.ToArray());
            System.IO.File.WriteAllText("sample.json", json);
        }

        public static void editvalues()
        {
            List<Data> _data = new List<Data>();
            _data.Add(new Data()
            {
                value = "off",
            });

            string json = JsonConvert.SerializeObject(_data.ToArray());
            System.IO.File.WriteAllText("sample.json", json);
        }
}

my json file goes from this

[{"value":"off","value2":"off"}]

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

to this

[{"value":"on","value2":null}]

and i want

[{"value":"on","value2":"off"}]

>Solution :

you have to parse json before changing

public static void editvalues()
{
    var json = File.ReadAllText("sample.json");
    Data[] data = JsonConvert.DeserializeObject<Data[]>(json);
    data[0].value = "on";
    json = JsonConvert.SerializeObject(data);
    File.WriteAllText("sample.json", json);
}

or this

public static void editvalues()
{
    var json = File.ReadAllText("sample.json");

    var jsonArray= JArray.Parse(json);
    jsonArray[0]["value"] = "on";

    WriteAllText("sample.json", jsonArray.ToString());
}
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