I use Newtonsoft.Json to serialize / deserialize objects.
As far as I know, deserialization cannot be successful if the class does not have a constructor without parameters. Example,
public class Dog { public string Name; public Dog(string n) { Name = n; } }
For this class below, the code correctly generates an object.
Dog dog1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Dog>("{\"Name\":\"Dog1\"}");
It is surprising to me that it correctly generates an object with lower codes.
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 I can think that
- Json converter ignores case sensitivity on reflection.
- Moreover, if it refers to the constructor, it fills the parameters with the json string (as if the parameter names are in the json string). Iβm not sure, but perhaps for this reason they call it flexible.
Here is 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 the created object gives me dog1.Name = "Dog1aaa" instead of dog1.Name = "Dog1" . How can I deserialize an object correctly (perhaps by overriding Name after creating the object)? Is there a way for strict deserialization?
Thanks in advance
serdar
source share