Home > OS >  Can a C# attribute be serialized into JSON?
Can a C# attribute be serialized into JSON?

Time:10-16

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.

CodePudding user response:

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