不要在外部条件下序列化字段 C#

Do not serialize fields under external conditions C#

我需要在 REST 响应中获取子集。我怎样才能达到那个目标? 例如,我们有 class:

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

和变量bool flag

在我的回复中,如果 flag 等于 true,我只需要 hrefid 字段。如果 flag 等于 false,我应该 return 所有字段。

我的GET方法是通过代码实现的:

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

此功能需要支持 fields 请求参数。

我找到了非序列化的 EmitDefaultValue 属性,但它只适用于默认值。

我应该自定义序列化程序还是数据属性?

这可以使用 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);
    }
}