Question

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.

Était-ce utile?

La solution

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; }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top