1

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

{ "value" : 1}
{ "valueFromOtherType" : 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.

4
  • 3
    Using Json.net you can do this using a JsonTextReader with the SupportMultipleContent flag set to true. See stackoverflow.com/q/38429059/10263. Note the example in the linked question uses a StringReader, but you can substitute a StreamReader instead. Commented Jul 16, 2021 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. Commented Jul 16, 2021 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). Commented Jul 16, 2021 at 23:03
  • For System.Text.Json perhaps this answer by Nathan to Line delimited json serializing and de-serializing does what you need. That question also has an answer for Json.NET so it might be a true duplicate. Commented Jul 17, 2021 at 0:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.