Question by
blairdubled · Jul 24, 2019 at 01:09 PM ·
c#serializationjsondeserialization
Null Exception while serialize json string into txt file
When I click button, it serialize flag variable to ".txt" file, my constructor deserializes. There is no problem with serialization , however my object "obj" is null although I attached them to be false or true, can you suggest a solution? (It won't try to read a blank file, handled with if statement below)
public UI()
{
InitializeComponent();
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);
File.WriteAllText(path_combined, json);
}
private void btn_test1_Click(object sender, EventArgs e)
{
//serialize
Serialize();
}
[Serializable]
class FlagClass
{
//command flags
[JsonProperty(PropertyName = "x")]
public bool SetLaser2Status1 { get; set; }
[JsonProperty(PropertyName = "y")]
public bool SetLaser2Status0 { get; set; }
public FlagClass()
}
Comment