Java 递归拆分 JSON 对象:按长度分割 JSON 数据
以下是使用递归方式拆分 JSON 的 Java 代码,将 JSON 拆分为指定长度的多个 JSON 对象:
import org.json.*;
public class JSONSplitter {
public static JSONArray splitJSONArray(JSONArray jsonArray, int maxLength) throws JSONException {
JSONArray result = new JSONArray();
int length = jsonArray.length();
if (length <= maxLength) {
result.put(jsonArray);
return result;
}
int start = 0;
while (start < length) {
int end = Math.min(start + maxLength, length);
JSONArray subArray = new JSONArray();
for (int i = start; i < end; i++) {
subArray.put(jsonArray.get(i));
}
result.put(subArray);
start += maxLength;
}
return result;
}
public static JSONObject splitJSONObject(JSONObject jsonObject, int maxLength) throws JSONException {
JSONObject result = new JSONObject();
for (String key : jsonObject.keySet()) {
Object value = jsonObject.get(key);
if (value instanceof JSONArray) {
result.put(key, splitJSONArray((JSONArray) value, maxLength));
} else if (value instanceof JSONObject) {
result.put(key, splitJSONObject((JSONObject) value, maxLength));
} else {
result.put(key, value);
}
}
return result;
}
}
使用示例:
String jsonString = '{"name": "John", "age": 30, "cars": ["Ford", "BMW", "Fiat", "Toyota", "Nissan", "Honda", "Chevrolet", "GMC", "Dodge"], "pets": {"dog": {"name": "Rex", "age": 5}, "cat": {"name": "Fluffy", "age": 3}}}';
JSONObject jsonObject = new JSONObject(jsonString);
int maxLength = 4;
JSONObject result = JSONSplitter.splitJSONObject(jsonObject, maxLength);
System.out.println(result.toString(4));
输出结果:
{
"name": "John",
"age": 30,
"cars": [
[
"Ford",
"BMW",
"Fiat",
"Toyota"
],
[
"Nissan",
"Honda",
"Chevrolet",
"GMC"
],
[
"Dodge"
]
],
"pets": {
"dog": {
"name": "Rex",
"age": 5
},
"cat": {
"name": "Fluffy",
"age": 3
}
}
}
在上面的例子中,原始 JSON 对象被拆分为长度为 4 的多个 JSON 对象。如果一个 JSON 数组的长度小于等于指定的长度,则该数组作为一个整体被拆分。如果一个 JSON 对象的某个值是另一个 JSON 数组或 JSON 对象,则该值也会被递归地拆分。最终拆分后的 JSON 对象被格式化为易于阅读的形式。
原文地址: https://www.cveoy.top/t/topic/ovm2 著作权归作者所有。请勿转载和采集!