>我有非常大的 json 字符串数组,并希望 HTTP post 请求在一次发布调用中最多接受 5 MB 数据,或者考虑每次调用 1000 条记录(大约(。
杰森:
Items:[
{"Name" : "Chair",
"price" : "30"},
{"Name" : "Table",
"price" : "40"},
{"Name" : "laptop",
"price" : "300"},
...
]
Java 片段:
public static void main(String args[]) throws Exception{
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);//5 secs
connection.setReadTimeout(5000);//5 secs
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write("json object");
out.flush();
out.close();
}
现在我一次发送所有json数组,有人可以帮我如何限制json数组,以便每次我可以批量发送1000条记录(大约(。
试试这个,
int batch_size = 1000;
Gson gson = new Gson();
JsonObject jsonObject = gson.fromJson(jsonObj, JsonObject.class);
JsonArray array = jsonObject.getAsJsonArray("items");
int numberOfBatches = array.size() / batch_size;
for(int i = 0; i <= numberOfBatches; i++) {
JsonArray currentBatch = new JsonArray();
for(int j = 0; (j < batch_size || j < array.size()); j++) {
currentBatch.add(array.get((i * batch_size) + j));
}
//Your POST code
JsonObject objtoSend = new JsonObject();
objtoSend.add("items", currentBatch);
out.write(gson.toJson(objtoSend));
...
}
它使用 Gson 库对数据进行序列化和反序列化。