System.Text.Json How to create customer converter that can use another converter?

Alex Oh 1 Reputation point
2021-07-19T18:34:11.98+00:00

I have a class which has a member that also needs a custom converter.

public class ClassA
{
    public int TypeDiscriminator { get; set; }

    // this member needs a custom converter
    public SourceCache<Property, string> Properties { get; set; }
    ....
}

ClassA also needs a custom converter because I want to support polymorphic deserialization.

// Read implementation inside ClassAConverter.cs

public override Sheet Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
    ....
    switch (propertyName) {
        case "Properties":
            if (reader.TokenType != JsonTokenType.StartObject)
                 throw new JsonException();

             ....

            // what do I need to do here to deserialize "Properties" which needs a custom converter?
     }
}

Now, I did write a custom converter for the SourceCache type, because I had earlier used the attribute [JsonConverter(typeof(SourceCacheConverter))] on the property, but, I realized I needed to support polymorphic deserialization.

Basically, my question is, is there a way to reuse the SourceCacheConverter inside the new ClassAConverter? If not, I suppose I can lift the SourceCacheConverter code and copy it over to the ClassAConverter Read method.

Developer technologies .NET Blazor
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2021-07-19T19:55:31.77+00:00

    Why can't you just instantiate the required converter inside your higher level converter?

    public class ClassAConverter : JsonConverter...
    {
       public override ... Read (...)
       {
          var childConverter = new ChildConverter(...);
       }
    }
    

    Alternatively you don't even need to do that if you're basing it strictly on type. If you have already registered a converter to handle the SourceCache<Propeprty> type then you can simply pass the sub-JSON string back to the JsonSerializer again and have it serialize the child object for you. Basically what you're doing at your highest level now.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.