문제

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.

도움이 되었습니까?

해결책

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; }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top