Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set requried field while Deserializing using Json.Net

I have a class Foo as follows

public class Foo
{
   public ClassA A {get;set;}
   public string B {get;set;}
}
public class ClassA
{
   public string C {get;set;}
}

When I get a Json string (say fooJson), I want to deserialize it to a Foo object with following conditions

  1. The object must have the property Foo.A
  2. Foo.B is optional
  3. Foo.A.C is optional

I tried using MissingMemberHandling = MissingMemberHandling.Error as a part of my JsonSerializerSettings. but that throws error even when Foo.B is missing.

like image 564
KnightFox Avatar asked Dec 05 '25 20:12

KnightFox


1 Answers

If you want some properties to be optional and some required, the easiest way to achieve this is to mark up your classes with [JsonProperty] attributes indicating which properties are required, e.g.:

public class Foo
{
    [JsonProperty(Required = Required.Always)]
    public ClassA A { get; set; }
    public string B { get; set; }
}
public class ClassA
{
    public string C { get; set; }
}
like image 169
Brian Rogers Avatar answered Dec 08 '25 11:12

Brian Rogers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!