gpt4 book ai didi

c# - 如果某个值不是 null,则隐藏 JSON 元素

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:59 25 4
gpt4 key购买 nike

有一个具有特定属性的 C# 类。在 HttpResponseMessage 中输出此类的对象时,我知道如果某个属性为 null,我们可以通过使用以下注释该属性来在 JSON 响应中隐藏该属性

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

有没有办法隐藏具有特定值的相同属性?例如如果其值为“网球”,不在 JSON 中显示 SportType 属性?

最佳答案

您可以使用 ShouldSerializeX 方法根据某些条件忽略属性的序列化。

public class SampleJsonClass
{
public int Id { get; set; }
public string Name { get; set; }

public bool ShouldSerializeName()
{
return (Name != "Tennis");
}
}

然后

var list = new List<SampleJsonClass>()
{
new SampleJsonClass() {Id = 1, Name = "Sample"},
new SampleJsonClass() {Id = 1, Name = "Tennis"}
};
var serializedJson = JsonConvert.SerializeObject(list);

输出

[
{
"Id":1,
"Name":"Sample"
},
{
"Id":1
}
]

关于c# - 如果某个值不是 null,则隐藏 JSON 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48463412/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com