Java 使用 JSONArray 和 JSONObject 合并数据
本文将介绍如何使用 Java 中的 JSONArray 和 JSONObject 类将一个 JSONArray 对象合并到另一个 JSONObject 对象中。
假设你有一个名为 data 的 JSONArray 对象,你需要将其合并到一个名为 tempData 的 JSONObject 对象中。你可以使用以下代码实现:
JSONArray outputArr = new JSONArray();
outputArr = joinJSONArray(outputArr, data);
JSONObject tempData = new JSONObject();
tempData.put('data', outputArr);
其中,joinJSONArray 方法将 data 中的数据合并到 outputArr 中。以下是 joinJSONArray 方法的实现:
public JSONArray joinJSONArray(JSONArray arr1, JSONArray arr2) {
for (int i = 0; i < arr2.length(); i++) {
arr1.put(arr2.get(i));
}
return arr1;
}
在代码执行之后,tempData 中的 'data' 字段将包含一个 JSONArray 对象,其中包含了 data 中的所有数据。
需要注意的是:
tempData是一个JSONObject对象,而不是JSONArray对象。- 确保
data是一个JSONArray对象,并且joinJSONArray方法的实现正确,才能正确地将data中的数据合并到tempData中。
希望本文对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/qBxa 著作权归作者所有。请勿转载和采集!