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.
3 Answers
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.

- 76,169
- 12
- 136
- 161
-
This was my thoughts to. Nice if there was a gson clone with this capability, will up one if I get that far – Erik Feb 16 '13 at 00:39
-
This only applies to Writer, not to Reader. – Yasir Ali Jun 16 '14 at 13:37
There is not a default way to get number of received bytes from JsonReader. I have written a little tricky Hack which is mentioned bellow:
Read bytes from inputstream and write them to an internal-storage file
while ((count = inputStream.read(data)) != -1) { total += count; final long downloadedLength = total; final long totalLength = lengthOfData; **// Here you get the size of bytes received** outStream.write(data, 0, count); }
Close all the opened streams (input and output streams created above)
Open the inputstream of newly created file
InputStream stream = mContext.openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(stream);Now you have an inputstream (stream) for JsonReader
Let JsonReader to use this inputstream for parsing data
After parsing completed, delete the file you created for temporary usage
InputStream stream = mContext.openFileInput(FILE_NAME);
InputStreamReader inputStreamReader = new InputStreamReader(stream);
jsonReader = new JsonReader(inputStreamReader);
parseMyJSON(jsonReader);File file = new File(mContext.getFilesDir(), FILE_NAME);
file.delete();

- 1,785
- 1
- 16
- 21
No way. Even if you wrap your input stream in some kind of wrapper to count bytes (e. g. apache's CountingInputStream), the results will be incorrect because of JsonReader's internal buffering. I've experimented with ~300 bytes long JSONs. CountingInputStream reported that ~4kb was read each time.

- 3,277
- 1
- 18
- 22