-1

I have a server which I do not control. I would like to interact with it by sending JSON requests and receiving JSON responses via TCP/IP socket. Let's assume UTF8 encoding is used and I have an open TCP connection with attached NetworkStream or SslStream called stream.

Sending part is simple and works perfectly:

var request = new TRequest();
JsonSerializer.Serialize(stream, request);

Ideally, I would like to receive a response in the following way:

TResponse response = JsonSerializer.Deserialize<TResponse>(stream);

This call hangs and there is a reason for that. It tries to do buffered reading from NetworkStream until the stream is finished, then it starts deserialisation (well, actually it splits it into chunks but it doesn't really matter here).

The problem is NetworkStream, in comparison to a file stream or something like that, is never ended (unless connection closed). On top of that I don't want to consume more data than really required for my object (to be able to read the following object from the same stream). That means workarounds that read network data to byte array first are not really helpful here.

JSON format contains all the information to indicate when the end of the object occurred, so I don't see any technical problem here.

What do I need to tell JsonSerializer to read the stream byte by byte without any buffering (not caring about performance) and stop as soon as the whole object has been read. Is there a possibility to do something like this by properly configuring either JsonSerializer or using it on top of some kind of non-buffering stream?

AndreyR
  • 301
  • 2
  • 10

1 Answers1

1

No, JsonSerializer.Deserialize reads the stream to completion, as the documentation states.

You would need to know the number of bytes to read or make a custom parser which analyzes the network stream and maps, i.e. cuts, it to multiple streams to provide to the JsonSerializer.

  • I don't know the number of bytes upfront. I believe it was possible to read it in a way I want using Json.Net. Is there a way in standard .Net JSON serialiser? – AndreyR Nov 26 '22 at 14:22
  • Have a look at [`DeserializeAsyncEnumerable`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserializeasyncenumerable?view=net-6.0#system-text-json-jsonserializer-deserializeasyncenumerable-1(system-io-stream-system-text-json-jsonserializeroptions-system-threading-cancellationtoken)) and/or [`Utf8JsonReader`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.utf8jsonreader?view=net-6.0), I am not sure if that would work, I have no experience with it. – Okke Hendriks Nov 26 '22 at 14:38
  • Also see this [SO question](https://stackoverflow.com/questions/58572524/asynchonously-deserializing-a-list-using-system-text-json). – Okke Hendriks Nov 26 '22 at 14:42