My code does (de)serialization of json strings. When user re-run the program, the previous data is fetched from txt file. I have two json string "json" and "json2", when I close and open program and look at txt file, json serialize and deserialze successfully while json2 is not.
I am new to json and c#, where is my flaw?
public Form1()
{
InitializeComponent();
input += ".txt";
//default path + new filename
path_combined = Path.Combine(root, input);
if (!File.Exists(path_combined))
{
//File.Create(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);
c1 = JsonConvert.DeserializeObject<Class1>(json2);
//Method used or not
string json = File.ReadAllText(path_combined);
FormatJson(json);
c2 = JsonConvert.DeserializeObject<Class1>(json);
}
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
c1.flag = true;
c1.flag2 = true;
c2.M1 = true;
string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
File.WriteAllText(path_combined, json);
string json2 = JsonConvert.SerializeObject(c2, Formatting.Indented);
File.WriteAllText(path_combined, json2);
}
class Class1
{
[JsonProperty(PropertyName = "flag")]
public bool flag { get; set; }
[JsonProperty(PropertyName = "flag2")]
public bool flag2 { get; set; }
public Class1()
{
}
}