var foos = new[] { new Foo { Age = 1, Name = "Should not show" }, new Foo { Age = 19, Name = "Name" } };
var result = JsonSerializer.Serialize(foos, new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers = { SkipUnderagedName }
}
});
Console.WriteLine(result); // prints "// [{"Age":1},{"Name":"Name","Age":19}]"
static void SkipUnderagedName(JsonTypeInfo ti)
{
if (ti.Type.IsAssignableTo(typeof(Foo)))
{
var prop = ti.Properties.FirstOrDefault(p => p.Name == nameof(Foo.Name));
if (prop is not null)
{
prop.ShouldSerialize = (obj, _) =>
{
var foo = obj as Foo;
return foo?.Age >= 18;
};
}
}
}
public class Foo
{
private string _name;
[System.Text.Json.Serialization.JsonPropertyName("Name")]
[System.Text.Json.Serialization.JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string _Name
{
get { return Age > 18 ? _name : null; }
set { _name = value; }
}
[System.Text.Json.Serialization.JsonIgnore]
public string Name
{
get { return _name; }
set { _name = value; }
}
public int Age { get; set; }
}
2条答案
按热度按时间mwkjh3gx1#
您可以为类型写入custom converter或使用.NET 7 approach with customizing contract:
8mmmxcuj2#
既然你不需要任何自定义的序列化器,你可以试试这段代码。如果年龄小于19岁,它返回Name属性值等于null。当Name为null时,序列化器忽略这个属性。