0

I am trying to find stream start and stop positions of JSON fragments.

At the moment I am using JsonTextReader which allows me to use the JsonTextReader.Path property which can be checked using a regex for matching. It does have LinePosition and LineNumber properties but these are of course for line-based character positions and not the byte stream positions.

The idea is to have fast lookup of JSON fragments using stream seeking (in practice using a substream that sees a slice of another stream, that's why I need the fragment start and stop positions in the underlying stream).

I have also tried System.Text.Json.JsonDocument which has a great API but unfortunateky reads all bytes into memory.

When fragments are looked up they are mapped into domain objects using System.Text.Json where memory consumption is less of an issue since its just fragments.

It is not directly possible to use JsonSerializer to deserialize the fragments, since custom fragment parsing/object-mapping happens using System.Text.Json.

Also, on .NET Framework 4.8, not .NET Core.

Bent Rasmussen
  • 5,538
  • 9
  • 44
  • 63
  • Json.NET doesn't report `Stream` positions because it doesn't work with streams or byte sequences, it works with `TextReader` and character sequences. Since `StreamReader` doesn't report the encoding mapping from `Stream` position to character index, neither does Json.NET. – dbc Jul 04 '20 at 16:02
  • 2
    If you're willing to switch to [tag:system.text.json] then `Utf8JsonReader` works directly with utf8 byte sequences and does report positioning via [`Utf8JsonReader.TokenStartIndex`](https://docs.microsoft.com/en-us/dotnet/api/system.text.json.utf8jsonreader.tokenstartindex?view=netcore-3.1#System_Text_Json_Utf8JsonReader_TokenStartIndex). `Utf8JsonStreamReader` from [this answer](https://stackoverflow.com/a/55429664/3744182) to [Parsing a JSON file with .NET core 3.0/System.text.Json](https://stackoverflow.com/q/54983533/3744182) is built on `Utf8JsonReader`, might that work for you? – dbc Jul 04 '20 at 16:06

0 Answers0