0

Suppose I have an input stream coming in that is a sequence of objects, like so:

{ "value" : 1}
{ "value" : 2}
{ "value" : 3}
{ "value" : 4}

How can I deserialize these objects in C#? Using System.Text.Json is preferred, Newtonsoft is fine. It would be straightforward if the data was wrapped in brackets, I could just deserialize into an array. But I don't have control on the incoming data stream.

Using System.Text.Json I could use JsonSerializer.DeserializeAsync, but only after I create my only stream class to wrap the existing data stream with brackets as it comes in. It'd still be a bit undesirable because I have to wait for the entire (synthetic) array to be read before I can look at the first element.

Frank Schwieterman
  • 24,142
  • 15
  • 92
  • 130
  • 2
    Using Json.net you can do this using a `JsonTextReader` with the `SupportMultipleContent` flag set to true. See https://stackoverflow.com/q/38429059/10263. Note the example in the linked question uses a `StringReader`, but you can substitute a `StreamReader` instead. – Brian Rogers Jul 16 '21 at 22:49
  • Thank you, my googling never would have crossed with that SO title. I would accept it as an answer, but consider value in having this form of the question be googleable and also would like to see if there is a System.Text.Json solution. – Frank Schwieterman Jul 16 '21 at 22:56
  • If you were just looking for a Newtonsoft-only answer I would consider it a duplicate, but since you are really looking for a System.Text.Json solution, I will not vote to close in case someone has a solution for that (I do not). – Brian Rogers Jul 16 '21 at 23:03
  • For `System.Text.Json` perhaps [this answer](https://stackoverflow.com/a/65604962/3744182) by [Nathan](https://stackoverflow.com/users/25182/nathan) to [Line delimited json serializing and de-serializing](https://stackoverflow.com/q/29729063/3744182) does what you need. That question also has an answer for Json.NET so it might be a true duplicate. – dbc Jul 17 '21 at 00:58

0 Answers0