简体   繁体   English

我可以使用Newtonsoft.Json进行严格的反序列化吗?

[英]Can I make a strict deserialization with Newtonsoft.Json?

I am using Newtonsoft.Json to serialize/deserialize objects. 我正在使用Newtonsoft.Json来序列化/反序列化对象。
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. Json转换器在进行反射时忽略了区分大小写。
  2. Moreover if it faces a constructor it fills parameters with json string(as if the parameter names are in json string). 此外,如果它面向构造函数,则使用json字符串填充参数(就好像参数名称在json字符串中一样)。 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" . 然后创建对象给我dog1.Name = "Dog1aaa"而不是dog1.Name = "Dog1" How can I deserialize the object correctly(maybe overriding Name after creating the object)? 如何正确反序列化对象(可能在创建对象后覆盖Name )? Is there a way for strict deserialization? 有没有办法严格反序列化?

Thanks in advance 提前致谢

How can I deserialize the object correctly(maybe overriding Name after creating the object)? 如何正确反序列化对象(可能在创建对象后覆盖Name)? Is there a way for strict deserialization? 有没有办法严格反序列化?

You can declare another constructor and force Json.Net to use it 您可以声明另一个构造函数并强制Json.Net使用它

public class Dog
{
    public string Name;

    [JsonConstructor]
    public Dog()
    {

    }

    public Dog(string name)
    {
        Name = name + "aaa";
    }
}

有这样的事情

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM