3

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.

KnightFox
  • 3,132
  • 4
  • 20
  • 35

1 Answers1

2

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; }
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300