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

如何向JSONArray添加多个JSONObject(不丢数据)并解析单个对象

JSONObject累积存储到JSONArray及解析实现方案

核心前提

要保证多次生成的JSONObject存入后历史数据不丢失,绝对不能在每次生成新JSONObject时重新初始化JSONArray实例,必须将JSONArray定义在多次表单处理逻辑可共享的作用域中:如果是单次请求内的多次表单处理,就放在请求上下文;如果是同用户跨请求的表单累积,就放在会话存储;如果需要永久留存,就持久化到数据库/缓存中,所有后续操作仅对该实例做追加,不做重建。

一、多JSONObject追加存储实现

  • 首次使用时初始化JSONArray实例,仅执行一次初始化逻辑,后续所有操作复用该实例
// 以通用org.json库为例,从共享作用域取已存在的数组实例
JSONArray formDataArray = (JSONArray) session.getAttribute("userFormDataCache");
// 仅当实例不存在时新建,避免覆盖历史数据
if (formDataArray == null) {
    formDataArray = new JSONArray();
    session.setAttribute("userFormDataCache", formDataArray);
}
  • 每次DAO层返回单条表单对应的JSONObject后,校验非空直接追加到已有的JSONArray实例中
// 调用DAO获取当前用户填写表单生成的单个JSONObject
JSONObject singleFormResult = formDao.generateFormData(requestParams);
// 追加到已存在的数组,原有数据不会被修改
if (singleFormResult != null) {
    formDataArray.put(singleFormResult);
    // 追加完成后更新共享作用域中的存储实例
    session.setAttribute("userFormDataCache", formDataArray);
}
  • 避坑提示:禁止每次获取到新JSONObject时执行JSONArray array = new JSONArray()的新建逻辑,该操作会生成空数组,覆盖此前存储的所有数据。

如果使用Fastjson、Jackson等其他JSON工具包,核心逻辑完全一致,仅部分方法名有差异:比如Fastjson用add()替代put()实现元素追加,不影响整体实现思路。


二、从JSONArray解析单个JSONObject的方法

  • 批量遍历解析:循环数组长度,按下标逐个取出元素,适合需要处理所有已存表单的场景
int totalSize = formDataArray.length();
for (int i = 0; i < totalSize; i++) {
    // 按下标取出单个JSONObject
    JSONObject currentForm = formDataArray.getJSONObject(i);
    // 按需解析单条表单内的字段,以提供的数据结构为例
    String clientCode = currentForm.getString("clientCode");
    String recId = currentForm.getString("recId");
    String corporateId = currentForm.getString("corporateId");
    JSONArray sections = currentForm.getJSONArray("contents");
    // 继续向下解析sections下的分区、表单项即可
}
  • 指定位置直取:如果明确需要获取的表单在数组中的序号,直接传入下标取值即可,注意提前校验数组长度避免下标越界
// 例如取用户第一次提交的表单数据
if (formDataArray.length() > 0) {
    JSONObject firstSubmitForm = formDataArray.getJSONObject(0);
}

附:单条表单JSONObject数据样例

{
    "contents": [
        {
            "sectionTitle": "Basic Info",
            "index": 0,
            "sectionId": "AU-BASIC-INFO",
            "fields": [
                {"name": "username", "type": "input", "value": "akhil"},
                {"name": "fullName", "type": "input", "value": "tester12"},
                {"name": "email", "type": "input", "value": "test@ecs.com"},
                {"name": "phone", "type": "input", "value": ""},
                {
                    "name": "role",
                    "options": [
                        {"label": "testing", "value": "931924ba-d1c5-4025-bf1c-01394ed3233a"},
                        {"label": "check", "value": "eef0b1d2-e468-4c70-a261-2e0b1001d816"},
                        {"label": "Creditor_Debtor_Maker_Authorizer__Self_Admin", "value": "5b5265f7-d883-4810-9dc1-ce313da971da"},
                        {"label": "SuperAdmins", "value": "88ob1be1-e80d-4189-962p-f60d667d02c8"},
                        {"label": "Test Ecs admin", "value": "c945184e-c044-4b15-9316-44a07b5fe0b3"},
                        {"label": "Administrator", "value": "b7ff1740-7dfc-434c-8d50-bb06f34ace19"},
                        {"label": "Authorizer", "value": "bf643fbb-c673-4023-b9d8-5d2163228723"}
                    ],
                    "type": "input",
                    "value": "931924ba-d1c5-4025-bf1c-01394ed3233a",
                    "isDisplay": true
                },
                {
                    "name": "userProfile",
                    "options": [
                        {"label": "Administrator", "value": "56068bb3-845f-415e-9c10-57e6e0ebf038"},
                        {"label": "Tenaga User profile", "value": "bedd8da6-615e-4e0c-8e0b-4a9a99e84888"},
                        {"label": "Tenaga Admin profile", "value": "a62d69b5-004a-4c58-83a8-39d009166ba8"},
                        {"label": "Tnadmin Profile", "value": "8ef85fd5-7a0c-41ae-a0d7-a77905f35b42"}
                    ],
                    "type": "input",
                    "value": "56068bb3-845f-415e-9c10-57e6e0ebf038",
                    "isDisplay": true
                }
            ]
        },
        {
            "sectionTitle": "Password",
            "index": 1,
            "sectionId": "AU-PASSWORD",
            "fields": [
                {
                    "name": "passwordType",
                    "options": [
                        {"label": "Manual Generate", "value": "01"},
                        {"label": "Auto Generate", "value": "02"}
                    ],
                    "type": "input",
                    "value": "01",
                    "isDisplay": true
                },
                {"name": "changePassword", "type": "input", "value": ""},
                {"name": "confirmPassword", "type": "input", "value": ""}
            ]
        },
        {
            "sectionTitle": "Preference",
            "index": 2,
            "sectionId": "AU-PREFERENCE",
            "fields": [
                {"name": "locale", "type": "input", "value": "en-us", "isDisplay": true},
                {"name": "dateFormat", "type": "input", "value": "dd-MM-yyyy", "isDisplay": true},
                {"name": "timeFormat", "type": "input", "value": "", "isDisplay": true},
                {"name": "numberFormat", "type": "input", "value": "", "isDisplay": true}
            ]
        }
    ],
    "clientCode": "BNPP",
    "recId": "f423c108-f920-4c66-a3e2-0dd8939e66b7",
    "corporateId": "04011000008"
}

内容的提问来源于stack exchange,提问作者akhil salil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 21:15:44