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"}]
to this
[{"value":"on","value2":null}]
and i want
[{"value":"on","value2":"off"}]
CodePudding user response:
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());
}
CodePudding user response:
You are overwriting the existing values with each edit because you are writing a new data object that doesnt have any context of what already exists in the file.
In order to get what you want, you should read the existing file contents first, convert them into your data object, modify the value you want changed, and write that data object to the file.