0

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?

Kate Lastimosa
  • 169
  • 2
  • 15
  • Assuming you're planning to write a method for that functionality, from where it will be consumed? Will it be exposed through a web api, or consumed by another piece of code within the solution etc? – vahdet Feb 21 '19 at 06:25

2 Answers2

0

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

PSK
  • 17,547
  • 5
  • 32
  • 43
0

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

Jay Bee
  • 35
  • 1
  • 1
  • 6