Kate Lastimosa
Kate Lastimosa

Reputation: 189

How to hide parts of a model when returning a response in Web API?

I have this reponse class:

public class Response
    {
        public bool isSuccess { get; set; }
        public string source { get; set; }
        public string number { get; set; }
        public string message { get; set; }

    }

if the response is successful i want to return only issuccess, source, number and not message. but when it fails i only want to return issuccess and message. is this possible? is there an attribute tag that can hide the objects when the value is null/empty?

Upvotes: 0

Views: 1890

Answers (2)

Jay Bee
Jay Bee

Reputation: 35

You can use DataContract/Datamemeber on your model.

[DataContract]
public class Response
{
    [DataMember(Name = "isSuccess")]
    public bool IsSuccess { get; set; }

    [DataMember(EmitDefaultValue = false, Name = "source")]
    public string Source { get; set; }

    [DataMember(EmitDefaultValue = false, Name = "number")]
    public string Number { get; set; }

    [DataMember(EmitDefaultValue = false, Name = "message")]
    public string Message { get; set; }
} 

Once you have your model populated make sure that based on your condition, unwanted properties are at their default values. In this case strings are null.

Additional advantage: Using data contract would also allow you to follow C# naming standards for your properties as well while keeping your JSON coming out as expected. illustrated in code above

Upvotes: 0

PSK
PSK

Reputation: 17943

To ignore all the time, you can use [ScriptIgnore] if you are using System.Web.Script.Serialization for Json.Net you can use attribute [JsonIgnore]

For conditional property serialization, you can use ShouldSerialize{PropertyName} which is accepted by most of the Serializer.

You can write your model like following.

 public class Response
        {
            public bool isSuccess { get; set; }
            public string source { get; set; }
            public string number { get; set; }
            public string message { get; set; }
            public bool ShouldSerializemessage()
            {
                return (!isSuccess); 
            }

            public bool ShouldSerializesource()
            {
                return (isSuccess);
            }
            public bool ShouldSerializenumber()
            {
                return (isSuccess);
            }
        }

You can read more about this here and here

Upvotes: 0

Related Questions