1

I'm creating API and need to give functionality like partial response. I know that in partial response, client/user need to pass the require parameter in controller method. But my case is little bit different. I need to create partial response based on the parameter name called package.

For example,

[Serializable]
[DataContract]
public class Class1
{
    [DataMember]
    public double? prop1 { get; set; }
    [DataMember]
    public string prop2 { get; set; }
    [DataMember]
    public DateTime? prop3 { get; set; }
    [DataMember]
    public double? prop4 { get; set; }
    [DataMember]
    public double? prop5 { get; set; }
    [DataMember]
    public double? prop6 { get; set; }
    [DataMember]
    public double? prop7 { get; set; }
    [DataMember]
    public double? prop8  { get; set; }
    [DataMember]
    public double? prop9  { get; set; }
    [DataMember]
    public double? prop10  { get; set; }
}

So, above Class1 is my base class which is called premium package. Now for Gold package I want few property from Class1 like prop1 to prop4. So my code would be something like this.

switch (`package`)  
{  
   case "Premium":  
      Fill the all properties of class1 
   break;  
   case "Gold":  
      Fill the few properties of class1  
   break;  
   case "Silver":  
         Fill the few properties of class2
   break;  
   default:  
      //TODO
   break;  
}  

So based on the packages, I want to return my response. But in response I want to add only those class property which is included in package. So is there any way to dynamically ignore the class property based on condition?

Even Ignoremember and JSONIgnore will solved my problem. But for that I need to create different class for different packages, that I don't want to do that.

Null value is acceptable.

CSDev
  • 3,177
  • 6
  • 19
  • 37
NETGeek
  • 219
  • 2
  • 15

1 Answers1

0

There's no true dynamic way to handle this, though you have a couple of options.

  1. You can rely on JSON.NET's NullValueHandling and DefaultValueHandling. You can add something like the following attribute to your class properties:

    [JsonProperty(NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore)]
    

    Then, you can conditionally only set the properties you want set. Anything that has a null or default value will be removed from the JSON response.

  2. You can utilize anonymous objects. Anonymous objects can be composed at a whim and the JSON serializer can still create a proper JSON response from them. So you can conditionally do something like:

    return Ok(new
    {
        Prop1 = something.SomeValue,
        Prop2 = something.SomeOtherValue,
        // etc.
    });
    

    That effectively allows you to create whatever response you like.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444