【问题标题】:Do not serialize fields under external conditions C#不要在外部条件下序列化字段C#
【发布时间】:2018-05-23 13:19:33
【问题描述】:

我需要在 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

在我的回复中,如果flag 等于true,我只需要hrefid 字段。如果flag 等于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# rest serialization request response


    【解决方案1】:

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

    【讨论】:

    • 不幸的是,它不适用于默认的序列化程序。我使用答案 link 来更改我的 GET 方法。之后它就可以工作了。
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 2020-01-21
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 2015-10-19
    相关资源
    最近更新 更多