Is there a way in Json.NET serialization to distinguish between “null because not present” and “null because null”?

后端 未结 5 893
日久生厌
日久生厌 2020-12-01 10:51

I\'m working in an ASP.NET webapi codebase where we rely heavily on the automatic support for JSON deserialization of message bodies into .NET objects via JSON.NET.

5条回答
  •  攒了一身酷
    2020-12-01 11:21

    Looking through the Json.NET source, I found that it supports populating bool properties with a suffix of "Specified" to indicate whether or not the property was included in the data:

    class MyClass
    {
        public string Field1 { get; set; }
    
        public Nested Nested { get; set; }
        public bool NestedSpecified { get; set; }
    }
    
    class Nested
    {
        public string Nested1 { get; set; }
        public string Nested2 { get; set; }
    }
    

    Input:

    {
      "field1": "my field 1",
      "nested": {
        "nested1": "something",
        "nested2": "else"
      }
    }
    

    Resulting instance:

    MyClass { Field1="my field 1", Nested=Nested { Nested1="something", Nested2="else" }, NestedSpecified=true }
    

    Input:

    {
      "field1": "new field1 value"
    }
    

    Resulting instance:

    MyClass { Field1="new field1 value", Nested=null, NestedSpecified=false }
    

    Input:

    {
      "nested": null
    }
    

    Resulting instance:

    MyClass { Field1=null, Nested=null, NestedSpecified=true }
    

    I can't find this functionality in the Json.NET documentation but it looks like it has been there since 2010.

提交回复
热议问题