javajsonjsonreader

How can I read MANY json objects from a file in Java?


The corresponding methods of JsonReader reader are followed by the rule that "this method needs to be called only once for a reader instance." Is there any standard tool to read from stream until it ends?


Solution

  • You may be able to repetitively construct multiple JsonReaders around the same InputStream / Reader. As long as you don't do anything else on the stream and as long as the parser doesn't read ahead, each successive parser should pick up where the last left off. Note that whether it might read ahead is undefined and may be implementation specific. Also note that it's common for parser implementations to close the stream/reader that they are given and you may need to suppress this by using a simple stream/reader wrapper that blocks close, like this:

    Json.createReader(new NoCloseInputStream(myInputStream));
    

    Otherwise, try a different parser. I have a FOSS JSON parser that can read a stream of discreet objects on my web site.

    Also, the documentation of JsonReader says the read() method need only be called once; it doesn't say it must only be called once, so it's worth trying to call read() repeatedly to see if it works. Nevermind; the methods are documented to throw an IllegalStateException if any of the read, readObject, readArray or close methods are called more than once.