I am using Newtonsoft.Json to serialize/deserialize objects.
As far as I know a deserialization can not be successful if the class does not have parameterless constructor. Example,
public class Dog
{
public string Name;
public Dog(string n)
{
Name = n;
}
}
For this class below code generates the object correctly.
Dog dog1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"Name\":\"Dog1\"}");
For me, surprisingly it generates the object correctly with below codes also.
Dog dog2 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"name\":\"Dog2\"}");
Dog dog3 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"n\":\"Dog3\"}");
Dog dog4 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"N\":\"Dog4\"}");
Now all I can think is
Here comes my question:
If my class is something like this,
public class Dog
{
public string Name;
public Dog(string name)
{
Name = name + "aaa";
}
}
and generating object with
Dog dog1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"Name\":\"Dog1\"}");
then created object gives me dog1.Name = "Dog1aaa"
instead of dog1.Name = "Dog1"
. How can I deserialize the object correctly(maybe overriding Name
after creating the object)? Is there a way for strict deserialization?
Thanks in advance
How can I deserialize the object correctly(maybe overriding Name after creating the object)? Is there a way for strict deserialization?
You can declare another constructor and force Json.Net to use it
public class Dog
{
public string Name;
[JsonConstructor]
public Dog()
{
}
public Dog(string name)
{
Name = name + "aaa";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With