Search code examples
javajsonbytegsonjsonreader

How can i see how many bytes was received from GSON JsonReader


While reading here and creating a large Object to send and receive using JsonWriter and JsonReader. I wanted to keep track of total bytes sent.


Solution

  • There's nothing in JsonWriter or JsonReader that is going to provide that for you.

    Really the only way to do it would be to wrap/extend the Reader or Writer you're currently passing to JsonReader/JsonWriter and keep track of the bytes being read/written in/out.

    Edit to add: As an example you could do something like:

    class MyWriterWrapper extends Writer {
    
        private Writer realWriter;
        private int bytesWritten;
    
        public MyWriterWrapper(Writer realWriter) {
            super(); 
            this.realWriter = realWriter;
        }
    
        public int getBytesWritten() {
            return bytesWritten;
        }
    
        @Override
        public Writer append(CharSequence csq) throws IOException {
             realWriter.append(csq);
             bytesWritten += csq.length();
             return this;
        }
    
        // Implement/Override all other Writer methods the same way
    
    }
    

    It'd be a lot cleaner if Writer was an interface but ... meh, what can you do. If you know you're only ever going to use one type of Writer (say, a BufferedWriter) you could extend that, override all the methods and re-call the methods on this instead of the private realWriter instance passed in via the constructor.