Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

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.

like image 477
FrozenHeart Avatar asked Aug 07 '14 12:08

FrozenHeart


People also ask

Which of the following attributes are required to ignore properties for JSON serializer?

To ignore individual properties, use the [JsonIgnore] attribute.

How does the Jsonproperty attribute affect JSON serialization?

JsonPropertyAttribute indicates that a property should be serialized when member serialization is set to opt-in. It includes non-public properties in serialization and deserialization. It can be used to customize type name, reference, null, and default value handling for the property value.

Which of the following attribute should be used to indicate the property must not be serialized while using JSON serializer?

Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.

Is JSON Net case sensitive?

SQL, by default, is case insensitive to identifiers and keywords, but case sensitive to data. JSON is case sensitive to both field names and data.


1 Answers

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)
like image 57
Brian Rogers Avatar answered Oct 12 '22 22:10

Brian Rogers