Home > Software engineering >  WPF/C# With Newtonsoft have a condition (if / else) before rewriting .json (true / false value)
WPF/C# With Newtonsoft have a condition (if / else) before rewriting .json (true / false value)

Time:11-03

I am a beginner and in a WPF application I need to rewrite an external json on only a few values. The values are only "true" and "false". Like that :

{
  "option1": false,
  "option2": false,
  "option3": true,
}

I only use buttons, for example "activate", "deactivate"

Using NewtonSoft.Json I found this method, which works and modifies the json well, but I don't know how to make a condition so that if the value is already "true" then a Messagebox says "The value is already true".

 private void Activate_Click(object sender, RoutedEventArgs e)
        {
            string myfile = "myfile.json";

            if (File.Exists(myfile))
            {
                string jsonString = File.ReadAllText(myfile);
                JObject jObject = JsonConvert.DeserializeObject(jsonString) as JObject;
                JToken jToken = jObject.SelectToken("option1");
                jToken.Replace(true);
                string updatedJsonString = jObject.ToString();
                File.WriteAllText(myfile, updatedJsonString);
                MessageBox.Show("Option true");
            }
            else
            {
                MsgError();
            }

        }

Thanks in advance for the help :)

CodePudding user response:

just cast jToken to bool

    if((bool)jToken)
    {
       MessageBox.Show("Option1 is true");
    }
  • Related