Reputation: 3
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?
Upvotes: 0
Views: 67
Reputation: 470
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);
}
}
Upvotes: 1