Using System.Text.Json, I have a class with some properties including System.Drawing.Font properties.
There’s no problem serializing it, but i can’t deserialize it.
I Get the error Deserialization of types without a parameterless constructor
Here is a simplified example :
When i click button1, i serialize the object, but i get the error when i click button2 to deserialize.
<code>using System.Text.Json;
namespace WinFormsApp1;
public partial class Form1 : Form
{
private CasaSettings _casaSettings;
private string _stringJson;
public Form1()
{
InitializeComponent();
_casaSettings = new CasaSettings();
}
private void button1_Click(object sender, EventArgs e)
{
_casaSettings.DefaultFont = textBox1.Font;
_stringJson = JsonSerializer.Serialize(_casaSettings, _casaSettings.GetType());
}
private void button2_Click(object sender, EventArgs e)
{
CasaSettings convertedSetting = (CasaSettings)JsonSerializer.Deserialize(_stringJson, typeof(CasaSettings));
}
}
public class CasaSettings
{
public CasaSettings() { }
public int AlertIntervalRefresh { get; set; } = 60000;
public Font DefaultFont { get; set; } = new Font("Tahoma", (float)8.25, GraphicsUnit.Point);
}
</code>
<code>using System.Text.Json;
namespace WinFormsApp1;
public partial class Form1 : Form
{
private CasaSettings _casaSettings;
private string _stringJson;
public Form1()
{
InitializeComponent();
_casaSettings = new CasaSettings();
}
private void button1_Click(object sender, EventArgs e)
{
_casaSettings.DefaultFont = textBox1.Font;
_stringJson = JsonSerializer.Serialize(_casaSettings, _casaSettings.GetType());
}
private void button2_Click(object sender, EventArgs e)
{
CasaSettings convertedSetting = (CasaSettings)JsonSerializer.Deserialize(_stringJson, typeof(CasaSettings));
}
}
public class CasaSettings
{
public CasaSettings() { }
public int AlertIntervalRefresh { get; set; } = 60000;
public Font DefaultFont { get; set; } = new Font("Tahoma", (float)8.25, GraphicsUnit.Point);
}
</code>
using System.Text.Json;
namespace WinFormsApp1;
public partial class Form1 : Form
{
private CasaSettings _casaSettings;
private string _stringJson;
public Form1()
{
InitializeComponent();
_casaSettings = new CasaSettings();
}
private void button1_Click(object sender, EventArgs e)
{
_casaSettings.DefaultFont = textBox1.Font;
_stringJson = JsonSerializer.Serialize(_casaSettings, _casaSettings.GetType());
}
private void button2_Click(object sender, EventArgs e)
{
CasaSettings convertedSetting = (CasaSettings)JsonSerializer.Deserialize(_stringJson, typeof(CasaSettings));
}
}
public class CasaSettings
{
public CasaSettings() { }
public int AlertIntervalRefresh { get; set; } = 60000;
public Font DefaultFont { get; set; } = new Font("Tahoma", (float)8.25, GraphicsUnit.Point);
}
I need to continue using System.Text.Json.
I think i need to use a converter but can’t make it work.
Thanks
2