【发布时间】:2021-09-08 10:23:20
【问题描述】:
如果另一个属性包含某个值,我需要能够序列化一个类并动态忽略某些属性(而不是将它们写到 JSON 中)。
所以想像下面的类:
public class MyClass
{
public List<string> Types { get; set; }
public string PropertyValidForType1 {get; set;}
public string PropertyValidForType2 {get; set;}
public string PropertyValidForType2 {get; set;}
}
如果我们在Type1 的Types 列表中有一个字符串,我希望将该属性序列化为 JSON 字符串,PropertyValidForType2 和 PropertyValidForType2 也是如此。
它们将是许多不需要序列化的属性,因此能够使用属性执行此操作将是有益的。我知道可以添加 [JsonIgnore] 属性,但这些属性不允许有条件地忽略属性。
这是我想要了解的示例
public class MyClass
{
public List<string> Types { get; set; }
[IncludeIfListIncludes(typeof(Types), "Type1")]
public string PropertyValidForType1 {get; set;}
[IncludeIfListIncludes(typeof(Types), "Type2")]
public string PropertyValidForType2 {get; set;}
[IncludeIfListIncludes(typeof(Types), "Type2")]
public string PropertyValidForType3 {get; set;}
}
var c = new MyClass
{
Types = new List<string> { "Type1", "Type3" },
PropertyValidForType1 = "A",
PropertyValidForType2 = "B",
PropertyValidForType3 = "C",
}
var jsonString = JsonSerializer.Serialize(weatherForecast);
Console.WriteLine(jsonString);
// Expected Output: { Types : [ "Type1", "Type3" ], PropertyValidForType1: "A", PropertyValidForType3: "C" }
上面的示例将跳过PropertyValidForType2 属性,因为列表中不包含Type2。
【问题讨论】:
-
你能解释一下,是Type属性依赖于其他字段的值,还是PropertyValidForType1/2/3值依赖于Types列表?
-
@IvanKhorin PropertyValidForType1/2/3 取决于类型列表中的特定类型。
标签: c# .net system.text.json