Can I do strict deserialization with Newtonsoft.Json?

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

+7
json c # json-deserialization
source share
2 answers

How can I deserialize an object correctly (possibly redefining the 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"; } } 
+7
source share

Something like that

 JsonConvert.DeserializeObject("json string", typeof(some object)); 
-one
source share

All Articles