1

The Utf8JsonReader has constructors to read from:

  • ReadOnlySpan<byte> jsonData
  • ReadOnlySequence<byte> jsonData

So what would be the best approach to read from a traditional StreamReader?

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
  • 1
    The premise of your question doesn't make sense. In essense, `Utf8JsonReader` already IS a reader, so passing it another reader is redundant. You can use the `JsonSerializer.Deserialize(Stream)` overloads instead, but again, those take the raw Stream source, not an instance of a reader wrapping the stream. – David L Mar 13 '23 at 19:08
  • There is an [open feature request](https://github.com/dotnet/runtime/issues/27156) for this to be added to the dotnet runtime. In the comments, AArnot has linked to [his own implementation](https://github.com/AArnott/Nerdbank.Streams/blob/main/doc/AsStream.md#readonlysequencebyte) as a reference – Andrew Williamson Mar 13 '23 at 19:12
  • 1
    @DavidL there are cases where you use two third-party libraries, one of which produces only `StreamReader` as output and another which only accepts `ReadOnlySequence` as input. In that case, you have to convert between the two. I've written code to do this myself in the past, but it would be nice to have native support – Andrew Williamson Mar 13 '23 at 19:16
  • What are you going to do with the `Utf8JsonReader` after you construct it? You may have somewhat of an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) here, `Utf8JsonReader` is quite low level. If you can tell us what you are trying to do we might be able to suggest an alternative using a higher-level API. – dbc Mar 13 '23 at 19:43
  • @AndrewWilliamson I understand your point, but even in that case, what you are fundamentally wanting to do is convert the underlying _stream_ to a `ReadOnlySequence`, which makes perfect sense to me. It is more about abstracting the stream from the `StreamReader` and converting it to `ReadOnlySequence` and yes, native support would be wonderful. – David L Mar 13 '23 at 21:37
  • @DavidL I just want to port this code from Newtonsoft to System.Text.Json: https://github.com/danipen/TextMateSharp/blob/master/src/TextMateSharp/Internal/Parser/Json/JSONPListParser.cs – Daniel Peñalba Mar 15 '23 at 08:31
  • 1
    @DanielPeñalba - the code at that link doesn't just construct a JSON reader from a `StreamReader`. It manually streams through the JSON and parses each token. System.Text.Json does not support that easily out of the box. But maybe [this answer](https://stackoverflow.com/a/55429664/3744182) by mtosh to [Parsing a JSON file with .NET core 3.0/System.text.Json](https://stackoverflow.com/q/54983533/3744182) does what you need. – dbc Mar 15 '23 at 18:06

0 Answers0