如何解决如何使用Java查找响应有效载荷JSON大小
我想确定使用Java的REST API的JSON响应有效负载大小。为了进一步描述,我必须设计一个批量API,该API可以从应用程序导出大数据,具有分页和安全性,但是我想限制单个页面的大小,以确保服务的连续性和性能输出。
在此方面对您的帮助表示感谢,
解决方法
您可能需要将其实际编码为JSON才能进行计算。数据模型可能无法准确指示通过JSON公开哪些属性,它们被称为什么或如何对其进行编码。
关于SO还有其他一些问题,问的大致相同,请参见 is there an easy way to estimate size of a json object?和 Calculate size in bytes of JSON payload including it in the JSON payload in PHP
您没有说出如何使用JSON,但是很可能是使用Jackson,甚至是Spring,因此类似的事情应该使您处于基本状态
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
characterCount
和byteCount
之间的区别可能并不明显,尤其是在您不习惯处理Unicode代码点的情况下。 HTTP Content-Length
指示八位字节的数量(字节),因此byteCount
最为准确,请参见What's the "Content-Length" field in HTTP header?。
服务器应在响应中设置Content-Length
标头(请参见https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length)。这是有效负载的大小(以字节为单位)。
因此,客户端可以像这样读取内容长度:
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.connect();
int length = connection.getContentLength();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。