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.
To ignore individual properties, use the [JsonIgnore] attribute.
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.
Apply a [JsonIgnore] attribute to the property that you do not want to be serialized.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With