Skip to content

Making Gson.fromJson(Reader, Class) return after one JSON value is read #1733

@TaylanUB

Description

@TaylanUB

When you pass a Reader to Gson.fromJson(), it seems to keep reading data until EOF or a syntax error. Perhaps this is desired in some scenarios, like strict error checking to ensure there's no superfluous data after the JSON value, but what if you want to read a JSON value that's just part of a longer-running stream?

It would be great if, as an optional setting, one could instruct Gson to stop reading from a reader after the end of a value is reached.

For all value types except Number, the end of the value is unambiguous: in case of an Array the closing square bracket, in case of an Object the closing curly brace, in case of a string the closing double quote, in case of booleans and null the end of the corresponding character string.

Numbers don't have an obvious end. Theoretically one could stop reading when the addition of the next digit would cause an overflow, but that might mask some actual errors. I have no opinion on how exactly the behavior should be because I don't think I'll ever need to read bare JSON numbers over a continuous stream; one can always wrap them in a one-element array or a trivial object like {"value":12345}.

Ensuring proper behavior would probably require the use of mark() and reset() on the reader. Once Gson has read a whole chunk of characters, it might realize that it's already read beyond the end of the JSON value. In that case it would need to count the number of characters that belong to the JSON value, reset() to before the last read() operation, and re-read only as many characters as it knows there exist until the end of the JSON value.

Thoughts?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions