You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现按索引合并两个JSON数组为JSONObject集合

没问题,我来帮你搞定这个数组合并的需求!既然你提到了JSONObject,我默认你是用Java的org.json库来处理JSON的(如果是其他JSON处理库比如Jackson、Gson,或者是前端JavaScript场景,我也给你补充对应的实现方案)。

Java 基于org.json库的实现方案

这是最贴合你提到的JSONObject的实现方式,先确保你的项目里引入了org.json依赖(Maven可以直接加对应的dependency):

import org.json.JSONArray;
import org.json.JSONObject;

public class ArrayMerger {
    public static void main(String[] args) {
        // 你的输入数组
        Integer[] idArray = {6, 7, 8, 9, 10, 11};
        Long[] timestampArray = {122402538L, 12240345L, 122496L, 122617L, 1227473L, 1228495L};
        
        // 关键校验:确保两个数组长度一致,避免索引越界
        if (idArray.length != timestampArray.length) {
            throw new IllegalArgumentException("两个输入数组的长度必须完全相同!");
        }
        
        // 存储最终结果的JSON数组
        JSONArray result = new JSONArray();
        
        // 遍历每个索引,配对生成JSONObject
        for (int i = 0; i < idArray.length; i++) {
            JSONObject item = new JSONObject();
            item.put("id", idArray[i]);
            item.put("timestamp", timestampArray[i]);
            result.put(item);
        }
        
        // 格式化输出结果(也可以直接返回result供后续使用)
        System.out.println(result.toString(2));
    }
}

运行这段代码后,你就能得到完全符合需求的JSON数组:

[
  {"id": 6, "timestamp": 122402538},
  {"id": 7, "timestamp": 12240345},
  {"id": 8, "timestamp": 122496},
  {"id": 9, "timestamp": 122617},
  {"id": 10, "timestamp": 1227473},
  {"id": 11, "timestamp": 1228495}
]
Java 基于Jackson库的实现方案

如果你的项目用的是更流行的Jackson库,实现逻辑类似,代码如下:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JacksonArrayMerger {
    public static void main(String[] args) throws Exception {
        Integer[] idArray = {6, 7, 8, 9, 10, 11};
        Long[] timestampArray = {122402538L, 12240345L, 122496L, 122617L, 1227473L, 1228495L};
        
        if (idArray.length != timestampArray.length) {
            throw new IllegalArgumentException("两个输入数组长度必须相同!");
        }
        
        ObjectMapper mapper = new ObjectMapper();
        ArrayNode result = mapper.createArrayNode();
        
        for (int i = 0; i < idArray.length; i++) {
            ObjectNode item = mapper.createObjectNode();
            item.put("id", idArray[i]);
            item.put("timestamp", timestampArray[i]);
            result.add(item);
        }
        
        // 格式化输出
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result));
    }
}
JavaScript 实现方案

如果是前端或者Node.js场景,用JavaScript可以更简洁地完成:

const ids = [6, 7, 8, 9, 10, 11];
const timestamps = [122402538, 12240345, 122496, 122617, 1227473, 1228495];

// 先做长度校验
if (ids.length !== timestamps.length) {
    throw new Error('两个数组长度必须一致!');
}

// 用map方法快速生成结果数组
const mergedResult = ids.map((id, index) => ({
    id: id,
    timestamp: timestamps[index]
}));

// 打印格式化后的结果
console.log(JSON.stringify(mergedResult, null, 2));

核心逻辑总结

不管用哪种语言或库,核心思路都是:

  1. 校验数组长度:避免因两个数组长度不一致导致的索引越界错误
  2. 遍历索引配对:将两个数组对应位置的元素取出,组装成指定结构的对象
  3. 收集结果:把所有组装好的对象放入数组中,得到最终的JSON集合

内容的提问来源于stack exchange,提问作者Jendorski Labs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:54:22