2

I'm trying to build a custom JSON Converter using the System.Text.Json library. A specific enhancement of the given converter needs to call an async method inside the public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) method (link to microsoft help page: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-converters-how-to?pivots=dotnet-5-0).

The easiest path would be to have the Read method marked as async, but I cannot due to the ref Utf8JsonReader parameter being ref (cannot have ref parameter in async method).

I've also looked for some other possibilities, like blocking the async call:

Like, I've read dozens of topic, and tried dozens of possible solution, but I had no luck with any of them. Therefore, I'm back to trying to see if it's possible to have the Read method marked as async is some way.. But I haven't found any solution so far.

Just to add one thing: I cannot rework my method to be NOT async.

Frankly, I'm not even sure this is possible, because even if marked async, I should be sure that the method that calls the converter awaits, which is an assumption I don't think I can make.
Therefore, I'm also open to some other suggestions or workaround for this.

EDIT: Due to the comment, I'm posting a sample code, but the complete example would be like my whole program. Therefore, I'm posting a simpler example:

public class TestJsonConverter : JsonConverter<string>
{

    private async Task<string> GetString()
    {
        await Task.Delay(500);
        return "Test";
    }

    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            string value = reader.GetString();
            // The following line is an error: cannot use `await` here.
            // Should mark the method as `async`, but cannot (can't even try because of the `ref` parameter.
            string valueEnhancned = value + await GetString();

            return valueEnhancned;
        }

        throw new Exception("invalid");
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        throw new NotImplementedException();
    }
}

As you can see, what I'd like to achieve is the call of GetString() inside the Read method. But, I cannot mark async that method.

EDIT2: Adding image to response a comment. As you can see, if the method is marked as async, it needs to return Task: enter image description here

dbc
  • 104,963
  • 20
  • 228
  • 340
Jolly
  • 1,678
  • 2
  • 18
  • 37

0 Answers0