7

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.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
Nishchal Sharma
  • 1,070
  • 9
  • 16

3 Answers3

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;
Community
  • 1
  • 1
2hamed
  • 8,719
  • 13
  • 69
  • 112
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