2

I want to determine JSON response payload size for REST API using Java. To describe further I have to design a bulk API that is exporting large data from application, pagination and security is in place but I want to limit the individual page size to ensure the service continuity and performance output.

your help in this regards is appreciated Thanks in advance!

PrashantT
  • 21
  • 1
  • 2
  • "your help in this regards is appreciated Thanks in advance!" can be removed. Just focus on the problem statement only. Please make your problem as concise and down to the point as possible. – DYS Aug 12 '20 at 06:25

2 Answers2

2

You're likely to need to actually encode it to JSON to be able to calculate that. The data model may not accurately indicate exactly what properties are exposed via JSON, what they're called, or how they're encoded.

There are a few other questions on SO asking roughly the same thing, see is there an easy way to estimate size of a json object? and Calculate size in bytes of JSON payload including it in the JSON payload in PHP

You don't say how you're using JSON, but it's fairly likely it's using Jackson, and perhaps Spring, so something like this ought to put you in the basic ballpark

ObjectMapper om = new ObjectMapper();
Object example = ... // the object you want to find the JSON size for

String jsonString = om.writeValueAsString(example); // get the JSON string
int characterCount = json.length(); // count the number of characters

byte[] bytes = om.writeValueAsBytes(example); // get the JSON as UTF-8 bytes
int byteCount = bytes.length; // count the number of bytes

The difference between characterCount and byteCount may not be obvious, especially if you're not used to dealing with Unicode code-points. HTTP Content-Length indicates the number of octets (bytes), so byteCount would be most accurate, see What's the "Content-Length" field in HTTP header?.

ptomli
  • 11,730
  • 4
  • 40
  • 68
1

The Server should set the Content-Length header in the response (see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length). This is the size of the payload in bytes.

So, the client can read the content length like this:

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
int length = connection.getContentLength();
Franz Deschler
  • 2,456
  • 5
  • 25
  • 39