简体   繁体   中英

Can a C# attribute be serialized into JSON?

I've made a class from the Attribute type

   public class DemoAttribute : Attribute {
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public string Label { get; private set; }

    public DemoAttribute(string label = null) {
        this.Label = label;
    }
}

When I try to serialize it with System.Text.Json

 var demo = new DemoAttribute("test");
 var json = JsonSerializer.Serialize(demo);

I get an InvalidOperationException:

Method may only be called on a Type for which Type.IsGenericParameter is true.

Can I serialize an Attribute without first copying it's properties to a 'regular' class with the same propeties?

Edit/Addition I'm using a far more extensive attribute with metadata on a property like (on the front end) what's the label, help-text, icon, validation rules, placeholder, etc. With reflection I get the attribute for the properties and I want to serialize it (the properties of the attribute) so I can send it to the front end.

Attribute has TypeId property which by default contains type of the attribute (see the remarks in docs), which fails during serialization when using System.Text.Json . You can override this property and ignore it:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM