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.
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.
Most helpful comment
@justinushermawan, did that help resolve your issue?
Also, it looks like you are passing the entire
byte[]to theJsonDocumentAPI (which contains the empty bytes).You probably want to do the following:
C# using JsonDocument jsonDocument = JsonDocument.Parse(bytes.AsMemory(0, request.Count));