Не десериализуется json c#
Есть websocket сервер на c# и клиент на python. При отправке json по websocket получаю ошибку десериализации на сервере:
info: Microsoft.Hosting.Lifetime[0]
Now listening on: https://localhost:8080
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:8000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /home/backend/WebSocket/WebSocket
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HM0UGBM202QI", Request id "0HM0UGBM202QI:00000001": An unhandled exception was thrown by the application.
System.Text.Json.JsonException: '0x00' is invalid after a single JSON value. Expected end of data. Path: $ | LineNumber: 0 | BytePositionInLine: 98.
---> System.Text.Json.JsonReaderException: '0x00' is invalid after a single JSON value. Expected end of data. LineNumber: 0 | BytePositionInLine: 98.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.ConsumeNextToken(Byte marker)
at System.Text.Json.Utf8JsonReader.ConsumeNextTokenOrRollback(Byte marker)
at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& readStack, JsonReaderException ex)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
at System.Text.Json.JsonSerializer.ParseCore(ReadOnlySpan`1 utf8Json, Type returnType, JsonSerializerOptions options)
at System.Text.Json.JsonSerializer.Deserialize[TValue](ReadOnlySpan`1 utf8Json, JsonSerializerOptions options)
at WebSocket.Middlewares.Pred.Echo(HttpContext context, WebSocket webSocket) in /home/backend/WebSocket/WebSocket/Middlewares/Pred.cs:line 28
at WebSocket.Startup.<>c.<<Configure>b__1_0>d.MoveNext() in /home/backend/WebSocket/WebSocket/Startup.cs:line 35
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
Код на c#:
using System;
using System.Net.WebSockets;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using WebSocket.Models;
namespace WebSocket.Middlewares
{
public static class Pred
{
static Encoding _encoding = Encoding.UTF8;
static RestClient _restClient = new RestClient();
public static async Task Echo(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
{
var buffer = new byte[1024 * 8];
var byteMessage = new byte[0];
int countMessage = 0;
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
var msg = JsonSerializer.Deserialize<Message>(buffer);
if (msg.Type == "GetEngines")
{
byteMessage = _encoding.GetBytes(JsonSerializer.Serialize(_restClient.Engines));
countMessage = JsonSerializer.Serialize(_restClient.Engines).Length;
}
else if (msg.Type == "GetMarkets")
{
await _restClient.GetMarkets(msg.Us);
byteMessage = _encoding.GetBytes(JsonSerializer.Serialize(_restClient.Markets));
countMessage = JsonSerializer.Serialize(_restClient.Markets).Length;
}
else if (msg.Type == "GetBoards")
{
await _restClient.GetBoards(msg.Us);
byteMessage = _encoding.GetBytes(JsonSerializer.Serialize(_restClient.Boards));
countMessage = JsonSerializer.Serialize(_restClient.Boards).Length;
}
else if (msg.Type == "GetSecurities")
{
await _restClient.GetSecurities(msg.Us);
byteMessage = _encoding.GetBytes(JsonSerializer.Serialize(_restClient.Securities));
countMessage = JsonSerializer.Serialize(_restClient.Securities).Length;
}
await webSocket.SendAsync(new ArraySegment<byte>(byteMessage, 0, countMessage), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
}
}
Код на python:
class App:
def __init__(self) -> None:
self.fragmentation = Fragmentation()
@staticmethod
async def main() -> None:
async with aiohttp.ClientSession() as session:
async with session.ws_connect('ws://localhost:8000/pred', ssl=False) as ws:
await ws.send_json({"type": "GetMarkets", "us":
{"engine": "stock", "market": None, "board": None, "security": None}})
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close cmd':
await ws.close()
break
else:
print(msg.data)
await ws.send_json({"type": "GetMarkets", "us":
{"engine": "stock", "market": None, "board": None, "security": None}})
elif msg.type == aiohttp.WSMsgType.ERROR:
break
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
app: App = App()
asyncio.run(app.main())
Ответы (1 шт):
Автор решения: Егор Кузнецов
→ Ссылка
Решилось подключением библиотеки using Newtonsoft.Json;
И изменением JsonSerializer.Deserialize<Message>(_encoding.GetString(buffer));
на JsonConvert.DeserializeObject<Message>(_encoding.GetString(buffer));