-1

I am making a PUT call to update user using url https://myWebsite.com/users with json body

[{
"Name" : "John",
}]

As I have not passed the "Status" attribute in json body, it is set as false by default as false is the default value of the Boolean data type.

But, I need to set it to true as the default value if the property is not passed in the json when making the API call.

I tried to use OnDeserializing attribute as below:

   [OnDeserializing]
    void BeforeDeserialization(StreamingContext ctx)
    {
        this.Status = true;
    }

but it was not working.

Model looks like below:

[DataContract (Namespace = "mynamespace")]
public class User
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public bool Status { get; set; }
}

Please help me with the issue.

CodeZila
  • 719
  • 1
  • 10
  • 27

3 Answers3

1

If you deserialize to a class, then in that class have a bool member that defaults to a true value. For instance:

public class NameAndStatus
{
    public string name { get; set;}
    public bool status { get; set; } = true;  // default value of true
}

If status is passed in with the json body, the member will be set to that passed in value. Otherwise you will get the default value, which is true.

Phillip Ngan
  • 14,101
  • 7
  • 65
  • 75
0

Let's try to use DefaultValueAttribute

Mixim
  • 974
  • 1
  • 10
  • 36
0

You can assign default value to boolean property Status like,

[DataContract (Namespace = "mynamespace")]
public class User
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public bool Status { get; set; } = true; 
                                    //^^^^^^^^ Set default value to Status property
}

In this way even if you pass value of Status property then default value will be replaced with actual value otherwise it will set value of Status to true.

CodeZila
  • 719
  • 1
  • 10
  • 27
Prasad Telkikar
  • 13,280
  • 4
  • 13
  • 37