My C#
class has the following structure
public class Example
{
public static Example Instance1 = new Example (0, "A");
public static Example Instance2 = new Example (1, "B");
protected Example(int value, string name)
{
this.value = value;
this.name = name;
}
private int value;
private string name;
}
Now I am trying to serialize Example.Instance1
as follows
var serializedVariable = JsonConvert.SerializeObject(Example.Instance1);
var OriginalVariable = JsonConvert.DeserializeObject<Example>(serializedVariable);
But it throws the exception that it does not have the constructor specified for JSON, but the value and name are lost in the deserialized version.
Now I added a parameter called [JsonConstructor]
for the constructor. It does deserialize successfully but the name and value are lost in the deserialized class.
Can you please help me with, how to serialize such class instances?