I want to calculate json array Size in KB/Mb. I have a condition where I need to calculate json Array size before uploading. It should not be more than 128 KB.
Asked
Active
Viewed 8,356 times
7
-
is the json array type String? or gson's JsonArray? or is it JSONArray from org.json package? Maybe you can post the relevant code so that we can see for ourselves? – Bhargav Dec 05 '16 at 08:58
-
Yes its JSONArray,not gson. – Nishchal Sharma Dec 05 '16 at 09:20
3 Answers
7
Convert your jsonArray
to String
and use string.getBytes().length
. It will give number of bytes used by the string to store the value.
Using those bytes you can calculate the size in any unit.
String.getBytes().length is the number of bytes needed to represent your string in the platform's default encoding. For example, if the default encoding was UTF-16 (rare), it would be exactly 2x the value returned by String.length(). More commonly, your platform encoding will be a multi-byte encoding like UTF-8.

Reaz Murshed
- 23,691
- 13
- 78
- 98

Nitesh
- 3,868
- 1
- 20
- 26
2
JSON is basically an String
and encodings determine how much memory is required to store a String
. Please read this first.
Now with that knowledge you can simply proceed as follow:
JSON.toString().getBytes(YOUR_PREFERRED_ENCODING).length;
1
you can use the File.length() method to get the file size in bytes.

Shekhar Tyagi
- 1,644
- 13
- 18
-
This solution need to generate the file but this could be useful in case of error to send the Json later without keeping it in memory. You should edit your answer to improve this a bit ;) – AxelH Dec 05 '16 at 09:16