Gerrit
Gerrit

Reputation: 651

Required Property and JSON PropertyName

I want to create a class with an required attribute and a mapped JSON name like the following:

class MyClass {
  [Required]
  public string Foo {get; set;}
}

This works all fine. But combining this with an JSON annotation like the following, breaks the validation

class MyClass {
  [Required]
  [JsonProperty(PropertyName = "bar")]
  public string Foo {get; set;}
}

Why does the behavior change here and how can I fix that?

Upvotes: 5

Views: 2093

Answers (1)

Mattias Larsson
Mattias Larsson

Reputation: 823

Try this:

class MyClass
{
    [JsonProperty(PropertyName = "bar", Required = Required.Always)]
    public string Foo { get; set; }
}

Upvotes: 3

Related Questions