Is the custom ITypeSerializer implementation in the docs safe to use in Prod?

In the docs for the .NET SDK, you provide an example of a custom ITypeSerializer implementation using System.Text.Json.

public class DotnetJsonSerializer : ITypeSerializer
{
    public T Deserialize<T>(ReadOnlyMemory<byte> buffer)
    {
        return JsonSerializer.Deserialize<T>(buffer.Span);
    }

    public T Deserialize<T>(Stream stream)
    {
        using var ms = new MemoryStream();
        stream.CopyTo(ms);
        var span = new ReadOnlySpan<byte>(ms.GetBuffer()).Slice(0, (int)ms.Length);
        return JsonSerializer.Deserialize<T>(span);
    }

    public ValueTask<T> DeserializeAsync<T>(Stream stream, CancellationToken cancellationToken = default)
    {
        return JsonSerializer.DeserializeAsync<T>(stream, null, cancellationToken);
    }

    public void Serialize(Stream stream, object obj)
    {
        using var jsonUtf8Writer = new Utf8JsonWriter(stream);
        JsonSerializer.Serialize(jsonUtf8Writer, obj);
    }

    public ValueTask SerializeAsync(Stream stream, object obj, CancellationToken cancellationToken = default)
    {
        return new ValueTask(JsonSerializer.SerializeAsync(stream, obj, null, cancellationToken));
    }
}

My question is, is the code provided in that example correct and safe for production (for KV gets and sets without projection)? What concerns me about the code is that in the doc’s explanation of the code, it refers to Google Gson. Goggle Gson has nothing to do with .NET, so its reference in the docs is clearly a mistake. It looks like that whole paragraph was copy and pasted from the Java docs. My concern is that the code following the explanation might also be incorrect/copy and pasted from the Java docs.

If your goal is to use a System.Text.Json serializer there is now a built-in one in the SDK. Just call Couchbase.Core.IO.Serializers.SystemTextJsonSerializer.Create(). It has a few overloads that take various parameters, including support for using a source-generated JsonSerializerContext.

https://docs.couchbase.com/sdk-api/couchbase-net-client/api/Couchbase.Core.IO.Serializers.SystemTextJsonSerializer.html

Yes, that is my goal.

Is that class safe to use in prod? The docs describe it as “experimental”.

So long as you accept the limitations, which are really limitations of System.Text.Json such as a lack of dynamic support, it should work great. Those are really limitations around corner cases mostly. We use it in production in some cases at my company. It’s also used for some of the SDK internals for the performance gains.

1 Like

Hi @jg2 -

Thanks for reporting. I created a ticket and we will get the incorrect docs addressed soon.

Jeff

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.