首页 > 解决方案 > 不要在外部条件下序列化字段C#

问题描述

我需要在 REST 响应中获取子集。我怎么能做到这一点?例如,我们有类:

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

和变量bool flag

在我的回复中,我只需要hrefid字段 if flagequals true。如果flagequals false,我应该返回所有字段。

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

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

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

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

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

标签: c#restserializationrequestresponse

解决方案


这可以使用 Newtonsoft 完成。https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

要有条件地序列化属性,请添加一个返回与属性同名的布尔值的方法,然后在方法名称前加上 ShouldSerialize。方法的结果决定了属性是否被序列化。如果方法返回 true 则该属性将被序列化,如果返回 false 则该属性将被跳过。

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);
    }
}

推荐阅读