c# - 不要在外部条件下序列化字段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
在我的回复中,我只需要href
和id
字段 if flag
equals true
。如果flag
equals 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
了非序列化的属性,但它只适用于默认值。
我应该自定义序列化程序还是数据属性?
解决方案
这可以使用 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);
}
}
推荐阅读
- javascript - Angular Renderer2 setStyle 函数可以对尚未定义样式属性的元素进行操作吗?
- ios - 更改已发布变量时,SwiftUI 视图未更新
- podman - 如何强制删除所有 podman 图像和子项
- java - System.out.println 在提供的 Stream 上不起作用?
- python - 如何在python中使用类似的switch case清除文本字段
- r - RStudio 查看器错误:未找到“会话/viewhtml ....”
- mysql - pdo 准备好的语句以无效的参数号退出
- azure - Azure 容器实例的静态 IP 地址
- impala - 在 Superset 上启用 Impala 模拟
- python - 在数据框列中选择并显示某个值