Question

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

  1. Json converter is ignoring case-sensitivity while doing reflection.
  2. Moreover if it faces a constructor it fills parameters with json string(as if the parameter names are in json string). I am not sure, but maybe this is the reason they call this flexible.

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

Was it helpful?

Solution

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";
    }
}

OTHER TIPS

With something like this

JsonConvert.DeserializeObject("json string", typeof(some object));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top