Runtime: JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions) failed to parse from WebSocket ReceiveAsync

Created on 19 Jun 2019  路  3Comments  路  Source: dotnet/runtime

JsonDocument.Parse(ReadOnlyMemory<Byte>, JsonReaderOptions) failed to parse from WebSocket message:

WebSocket ws = await context.WebSockets.AcceptWebSocketAsync();
byte[] bytes = new byte[1024 * 4];
ArraySegment<byte> buffer = new ArraySegment<byte>(bytes);

while (ws.State == WebSocketState.Open)
{
       try
       {
             WebSocketReceiveResult request = await ws.ReceiveAsync(bytes, CancellationToken.None);
             switch (request.MessageType)
             {
                     case WebSocketMessageType.Text:
                             string msg = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                             json = new ReadOnlyMemory<byte>(bytes);
                             JsonDocument jsonDocument = JsonDocument.Parse(json);
                             break;
                     default:
                             break;
             }
       }
       catch (Exception e)
       {
             Console.WriteLine($"{e.Message}\r\n{e.StackTrace}");
       }
 }

Exception thrown:
'0x00' is invalid after a single JSON value. Expected end of data. LineNumber: 0 | BytePositionInLine: 34.

area-System.Text.Json

Most helpful comment

@justinushermawan, did that help resolve your issue?

Also, it looks like you are passing the entire byte[] to the JsonDocument API (which contains the empty bytes).

You probably want to do the following:
C# using JsonDocument jsonDocument = JsonDocument.Parse(bytes.AsMemory(0, request.Count));

All 3 comments

string msg = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

bytes.Length should be request.Count?

@justinushermawan, did that help resolve your issue?

Also, it looks like you are passing the entire byte[] to the JsonDocument API (which contains the empty bytes).

You probably want to do the following:
C# using JsonDocument jsonDocument = JsonDocument.Parse(bytes.AsMemory(0, request.Count));

Finally I resolved this by slicing the bytes start from index 0 to request.Count. Thanks everyone.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yahorsi picture yahorsi  路  3Comments

nalywa picture nalywa  路  3Comments

aggieben picture aggieben  路  3Comments

v0l picture v0l  路  3Comments

omariom picture omariom  路  3Comments