runtime: ',' is invalid after a single JSON value. Expected end of data.

I am reading a single complex object from a FileStream using JsonSerializer.ReadAsync<T>(stream, options, token) and I seriously just want the one value, but I am getting this exception.

',' is invalid after a single JSON value. Expected end of data.

The JSON in the file is preceded by bytes which I have skipped or already processed and it is followed by more bytes which I can skip or process separately. However I get stuck by this exception and don’t get the value that is presumably correctly read.

I have no idea how long the value is. Pre-parsing the JSON at a lower level to just get the byte length is a bad solution.

Wouldn’t it be better to not throw in this situation and let the consumer of the API choose to check for end of stream?

Similar to dotnet/runtime#29947.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 30 (21 by maintainers)

Most upvoted comments

It’s good to point this out in case people with corrupt data end up on this issue by searching for the error message, but I want to make it clear that this issue isn’t about corrupt data, but about a design limitation in System.Text.Json that makes it impossible to intentionally decode a JSON value from the middle of a stream.

Note that there is another approach you can use: call stream.SetLength(stream.Position) after serializing to it but before closing the file.

Mm, DeserializeAsyncEnumerable I believe does cover my usage. It only applies to arrays at the root, but that’s precisely my situation.