我有非常大的json字符串数组,并希望HTTP post请求在一次调用后接受最多5 MB的数据,或者考虑每次调用1000条记录(大约)。
JSON:
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条记录(大约)。
答案 0 :(得分:0)
试试这个,
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库来序列化和反序列化数据。