Hello,
My code fails to serialize(or maybe because of the deserialize), my logic is: When I open the program, constructor reads the previously saved values from text file. That is why I put deserialization there. And whenever a bool value is changed, I immediately serialize it.
I read other questions that is why I did my deseriazliation in this way.
I checked if the problem stems from File.WriteAllText(path_combined, json); , it overwrites if file exists, it shouldn't create problem.
My current txt file show the bool variables set to false and won't change. Doe sit has to do with my "json2", I am not sure, I stuck.
[Serializable]
public partial class UI: Form {
string input = Interaction.InputBox("Enter a serial number", "TEST", "Default", -1, -1);
//DEFAULT PATH ROOT
String root = @".\\";
string path_combined;
FlagClass obj;
public UI() {
InitializeComponent();
obj = new FlagClass();
foreach(string s in SerialPort.GetPortNames()) {
cbxPort.Items.Add(s);
cbxPort.SelectedIndex = 0;
}
input += ".txt";
//default path + new filename
path_combined = Path.Combine(root, input);
if (!File.Exists(path_combined)) {
using(var stream = File.Create(path_combined)) {
//if (new FileInfo(path_combined).Length > 0)
//flag situation
string json2 = File.ReadAllText(path_combined);
FormatJson(json2);
obj = JsonConvert.DeserializeObject < FlagClass > (json2);
}
}
else {
//flag situation
string json2 = File.ReadAllText(path_combined);
FormatJson(json2);
obj = JsonConvert.DeserializeObject < FlagClass > (json2);
}
}
private static string FormatJson(string json) {
dynamic parsedJson = JsonConvert.DeserializeObject(json);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
void Serialize() {
string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
File.WriteAllText(path_combined, json);
}
private void btn_test1_Click(object sender, EventArgs e) {
obj.flag = true;
Serialize();
}
[Serializable]
class FlagClass {
//command flags
[JsonProperty(PropertyName = "flag")]
public bool flag {
get;
set;
}
public FlagClass() {
}