0

I need to get subset in the REST response. How I can reach that? For example, we have class:

[DataContract]
public class Response
{
    [DataMember]        
    public string id { get; set; }
    [DataMember]
    public string href { get; set; }
    [DataMember]
    public string name { get; set; }
}

And variable bool flag

In my response I need only href and id fields if flag equals true. And if flag equals false, I should return all fields.

My GET method is implemented through the code:

public interface IRestServiceImpl
{    
    [OperationContract]        
    [WebInvoke(Method = "GET",
         ResponseFormat = WebMessageFormat.Json,
         RequestFormat = WebMessageFormat.Json,
         BodyStyle = WebMessageBodyStyle.Bare,
         UriTemplate = "Response/{*id}?fields={fieldsParam}")]
}

This functionality is need for supporting fields request param.

I found EmitDefaultValue attribute for non serialization, but it works only with default values.

Should I customized serializer or data attributes?

1 Answers1

1

This can be done using Newtonsoft. https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

To conditionally serialize a property, add a method that returns boolean with the same name as the property and then prefix the method name with ShouldSerialize. The result of the method determines whether the property is serialized. If the method returns true then the property will be serialized, if it returns false then the property will be skipped.

public class Employee
{
    public string Name { get; set; }
    public Employee Manager { get; set; }

    public bool ShouldSerializeManager()
    {
        // don't serialize the Manager property if an employee is their own manager
        return (Manager != this);
    }
}
Joakim M. H.
  • 424
  • 4
  • 14
  • Unfortunatly, it doesn't work with the default serializer. I use answer [link](https://stackoverflow.com/questions/3118504/how-to-set-json-net-as-the-default-serializer-for-wcf-rest-service) to change my GET method. After that it works. – Artyom Valeev May 23 '18 at 14:39