0

There is a custom attribute I created that I prescribe to classes for the markup extension.

I used to use the serialization mechanism through Newtonsoft.Json and I want to switch to Text.Json, but I ran into a problem that it throws exceptions when trying to serialize classes that inherit from Attribute

public class ConfigNameAttribute : Attribute
  {
    public ConfigNameAttribute(string name, bool enable)
    {
      this.name = name;
      this.enable = enable;
    }

    public string name { get; set; }
    public bool enable { get; set; }
  }
var text = JsonSerializer.Serialize(temp);

throws an exception

System.InvalidOperationException: 'Method may only be called on a Type for which Type.IsGenericParameter is true.'

if you remove Attribute then everything is fine

Magals
  • 23
  • 5
  • 1
    The problem is caused by `Attribute.TypeId` returning `GetType()` by default, and System.Text.Json does not support serializing or deserializing `Type` objects. Demo here: https://dotnetfiddle.net/6Eur4o. Json.NET serializes `TypeId` as follows: `"TypeId":"ConfigNameAttribute, 3wduoyfp.exe, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"`. – dbc Aug 13 '22 at 00:38
  • 1
    oh right. for Newtonsoft.Json i write JsonSerializerSettings settings = new JsonSerializerSettings(); settings.Formatting = Formatting.Indented; settings.ContractResolver = new DictionaryAsArrayResolver(new string[] { "TypeId", }); but for Text.Json I don't find such approach – Magals Aug 13 '22 at 01:24
  • 2
    found, it was necessary to put the option System.Text.Json.JsonSerializer.Serialize(temp, new JsonSerializerOptions() { IgnoreReadOnlyProperties = true }); – Magals Aug 13 '22 at 01:48

0 Answers0