mardi 29 mars 2022

.NET 6 Reflection : programmatically call JsonConverter Write method

I have a JsonConverter with a Write method :

  public class CollectionRowGuidConverter<T> : JsonConverter<ICollection<T>> where T : RowGuid
  {

    (...)

    public override void Write(Utf8JsonWriter writer, ICollection<T> value, JsonSerializerOptions options)
    {...}
}

I have a class with a property and a JsonConverter as attribute :

[JsonConverter(typeof(CollectionRowGuidConverter<Group>))]
public List<Group> Groups
{ ... }

By reflection, I have a PropertyInfo on this Groups property, how can I call the write method of the JsonConverter ?

  if (propertyInfo.Name == "Groups")
    {
      var attribute = propertyInfo.GetCustomAttributes().FirstOrDefault();
      if (attribute is JsonConverterAttribute)
      {
        var converter = (attribute as JsonConverterAttribute).CreateConverter(propertyInfo.PropertyType);
        if (converter.CanConvert(propertyInfo.PropertyType))
        {
          //converter.Write(...)
        }
      }
    }




Aucun commentaire:

Enregistrer un commentaire