我已经从属性类型
创建了一个类public class DemoAttribute : Attribute {
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Label { get; private set; }
public DemoAttribute(string label = null) {
this.Label = label;
}
}
当我尝试用System.Text.Json序列化它时
var demo = new DemoAttribute("test");
var json = JsonSerializer.Serialize(demo);
我得到InvalidOperationException:
方法只能在Type为的类型上调用。IsGenericParameter是真的。
我可以序列化一个属性,而不首先复制它的属性到一个"常规"类具有相同的属性?
编辑/添加我使用了一个更广泛的属性,在属性上有元数据,比如(在前端)标签、帮助文本、图标、验证规则、占位符等。通过反射,我得到了属性的属性,我想序列化它(属性的属性),这样我就可以把它发送到前端。
Attribute
具有TypeId
属性,默认包含属性类型(参见文档中的注释),当使用System.Text.Json
时,该属性在序列化期间失败。您可以重写此属性并忽略它:
public class DemoAttribute : Attribute
{
[JsonIgnore]
public override object TypeId { get; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public string Label { get; private set; }
public DemoAttribute(string label = null)
{
this.Label = label;
}
}