Search code examples
c#jsonjson.net

Should I set any attribute for the optional fields in case of JSON.NET


Should I set any attribute for the optional fields in case of JSON.NET deserialization? I mean something like

public class Foo
{
    [JsonProperty(Required = Required.Default)]
    public String foo { get; set; }
}

Thanks in advance.


Solution

  • If your class has a property that the JSON does not, then that property will have a default value in your class after deserialization. If your JSON has a property that your class does not, then Json.Net will simply ignore that property during deserialization. You do not need to do anything special to handle it.

    You can write simple test code to prove this out. Here we have a class Foo which has properties A and C, while the JSON we want to deserialize has properties A and B. When we deserialize, we see that A is populated, B is ignored (not in the class) and C has a default value of null (not in the JSON).

    class Program
    {
        static void Main(string[] args)
        {
            string json = @"{ ""A"" : ""one"", ""B"" : ""two"" }";
    
            Foo foo = JsonConvert.DeserializeObject<Foo>(json);
    
            Console.WriteLine("A: " + (foo.A == null ? "(null)" : foo.A));
            Console.WriteLine("C: " + (foo.C == null ? "(null)" : foo.C));
        }
    
        class Foo
        {
            public string A { get; set; }
            public string C { get; set; }
        }
    }
    

    Output:

    A: one
    C: (null)