SignalR with JsonProtocol throws System.Text.Json.JsonException: ‘{‘ is invalid after a value

Issue

This Content is from Stack Overflow. Question asked by Sylvain Gantois

In .Net 6, when trying to use SignalR with JsonProtocol (System.Text.Json), my client program throws the following exception

System.IO.InvalidDataException: Error reading JSON.
   ---> System.Text.Json.JsonException: '{' is invalid after a value. Expected either ',', '}', or ']'. Path: $ | LineNumber: 0 | BytePositionInLine: 4090

Code on server side:

services.AddSignalR()
    .AddJsonProtocol();

Code on client side:

conn = new HubConnectionBuilder()
        .WithUrl($"{_serverBaseAddress}mainHub", o =>
            {
                o.AccessTokenProvider = InitializeOrRefreshAccessTokenIfNeeded;
                o.Transports = HttpTransportType.WebSockets;
            }
        )
        .ConfigureLogging(logging =>
        {
            logging.AddConsole();
        })
        .AddJsonProtocol()
        .Build()

Note: everything works fine when using NewtonsoftJsonProtocol:

Code on server:

services.AddSignalR()
        .AddNewtonsoftJsonProtocol(opts =>
        {
            opts.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.All;
        });

Code on client:

conn = new HubConnectionBuilder()
        .WithUrl($"{_serverBaseAddress}mainHub", o =>
            {
                o.AccessTokenProvider = InitializeOrRefreshAccessTokenIfNeeded;
                o.Transports = HttpTransportType.WebSockets;
            }
        )
        .ConfigureLogging(logging =>
        {
            logging.AddConsole();
        })
        .AddNewtonsoftJsonProtocol(
        opts =>
            opts.PayloadSerializerSettings.TypeNameHandling = TypeNameHandling.All
        )
        .Build();

There is a difference, with NewtonsoftJson I specify TypeNameHandling.All but I do not know any equivalent for System.Text.Json.

Why not just keep Newtonsoft.Json? I would like to use source generators and specify a SerializerContext like below:

.AddJsonProtocol(options =>
{
    options.PayloadSerializerOptions.AddContext<MyJsonSerializerContext>();
});

which I believe I cannot do with NewtonsoftJson



Solution

Check the Answers

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?