1

I'm trying to read a sequence of JSON objects from a network stream. This involves finding complete JSON objects and returning them one by one. As soon as a complete JSON object was received, I need to have it. Anything else that follows that JSON object is for the next object and must only be used when the next complete object was received.

I would have thought that the Utf8JsonReader class could do that but apparently it cannot accept a Stream of any kind. It even seems to be unwanted to have that possibility.

Now I'm wondering if it's possible at all to use .NET's shiny new JSON parser to read from a stream when I don't know when data arrives and how much of it. Do I need to split the JSON object messages manually or can the already existing reader just stop when it has something and continue when the next thing is available? I mean, if it can do that on a predefined array of bytes, it could surely also do it with some waiting in between until more data is available. That just doesn't seem to be exposed in the public API. Or did I miss something?

The JsonDocument.ParseAsync(Stream) method cannot be used because it would read the stream to the end. That doesn't make sense for a network stream that stays open for a long time and just reads some data from time to time.

ygoe
  • 18,655
  • 23
  • 113
  • 210
  • [Parsing a JSON file with .NET core 3.0/System.text.Json](https://stackoverflow.com/q/54983533/3744182) may be what you need. – dbc Dec 20 '22 at 00:36
  • That code is longer than when I split the stream with my code. And I don't even know what it does or needs. I don't know where the end of the JSON element is; the parser needs to find it and next time read from there on. – ygoe Dec 20 '22 at 08:44
  • In the answer mentioned above, there is another one with reference to _JsonSerializer.DeserializeAsyncEnumerable_, I think this what you need to use. – Monsieur Merso Dec 25 '22 at 16:53

0 Answers0