Home > Back-end >  WPF/C# Textbox.Text Don't grab quotes while rewriting json
WPF/C# Textbox.Text Don't grab quotes while rewriting json

Time:03-22

In an application I modify an external json which contains several options parameters for another application. I am using deserialization with Newtonsoft to modify different lines. On one, I use in .xaml a <TextBox> in which a numerical value is entered. A button, next to it, allows you to validate the number.

I retrieve when the application is launched what the json indicates to fill the TextBox :

JToken optionnumeric= jObject.SelectToken("option");             
TextBox.Text = optionnumeric.ToString();

The user enters the numerical value that suits him and clicks on the button to validate. Here is the button code:

private void SetNumericValue(object sender, RoutedEventArgs e)
{             
    if (int.Parse(TextBox.Text) > 1000)             
    {                 
    TextBox.Text = "1000";             
    }             
    else if (int.Parse(TextBox.Text) < 1)             
    {                 
    TextBox.Text = "1";             
    }             
    string jsonString = File.ReadAllText("myjson.json");             
    JObject jObject = JsonConvert.DeserializeObject(jsonString) as JObject;             
    JToken jToken = jObject.SelectToken("option");             
    jToken.Replace(TextBox.Text);             
    string updatedJsonString = jObject.ToString();             
    File.WriteAllText("myjson.json", updatedJsonString);         
}

The problem is that originally, in the json, the option is like this:

"option": 500,

When rewriting with the application, it adds quotes:

"option": "500",

And I really don't see how to stop it from putting those double quotes.

First thank you for taking the time to read my problem.

And thank you in advance to anyone who can help me.

CodePudding user response:

rework your code to hang onto your parsed int:

private void SetNumericValue(object sender, RoutedEventArgs e)
{             
    var intValue = int.Parse(TextBox.Text);

    if (intValue > 1000)             
    {                 
        intValue = 1000;             
    }             
    else if (intValue < 1)             
    {                 
        intValue = 1;             
    }             

    string jsonString = File.ReadAllText("myjson.json");             
    JObject jObject = JsonConvert.DeserializeObject(jsonString) as JObject;             
    JToken jToken = jObject.SelectToken("option");             
    jToken.Replace(intValue);             
    string updatedJsonString = jObject.ToString();             
    File.WriteAllText("myjson.json", updatedJsonString);

    TextBox.Text = intValue.ToString();         
}

using jToken.Replace(intValue) will write the value without quotes as it is an integer type. Note - there is no validation checking on the int.Parse. That'd be good to add.

  • Related