Can I make a strict deserialization with Newtonsoft.Json?

孤街浪徒 提交于 2019-12-30 17:57:04

问题


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


回答1:


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



回答2:


With something like this

JsonConvert.DeserializeObject("json string", typeof(some object));


来源:https://stackoverflow.com/questions/22096427/can-i-make-a-strict-deserialization-with-newtonsoft-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!