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

如何在Java中通过AccountId映射将JSONObject转换为目标JSONObject

Mapping JSON Objects by AccountId in Java

Hey there! Let's break down how to take your nested JSON structure and transform it into a unified format grouped by accountId. I'll use the org.json library (a common, straightforward choice for JSON handling in Java) to walk you through a practical, step-by-step solution.

First, let's clarify our end goal: we want to combine data from the accountnames, sales, and countResult arrays into a single collection where each entry holds all related data for a unique accountId—even if some fields are missing for certain IDs.

Step-by-Step Solution

1. Parse the Original JSON

First, we'll convert your input JSON string into a JSONObject so we can access the nested arrays easily.

2. Use a Map to Group Data by AccountId

We'll leverage a Map<Integer, JSONObject> where the key is the accountId, and the value is a JSONObject that accumulates all data for that account. This makes it simple to look up and update entries as we iterate through each array.

3. Iterate Through Each Array and Populate the Map

We'll loop through each of the three arrays, adding or updating the corresponding entry in the map. For accounts that only exist in one array (like ID 878489, which only appears in countResult), we'll still include them with their available fields.

4. Convert the Map to the Final JSON Structure

Once all data is grouped, we'll convert the map values into a JSON array and wrap it in a clean final result object.

Full Code Example

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class AccountDataMapper {
    public static void main(String[] args) {
        // Your input JSON string
        String inputJson = "{ \"result\": { \"accountnames\": [{ \"accountName\": \"Hari\", \"accountId\": 878488 }, { \"accountName\": \"ravi\", \"accountId\": 878487 }], \"sales\": [{ \"accountSales\": \"89\", \"accountId\": 878488 }, { \"accountSales\": \"98\", \"accountId\": 878487 }], \"countResult\": [{ \"accountResult\": \"945\", \"accountId\": 878488 }, { \"accountResult\": \"9452\", \"accountId\": 878489 }] } }";

        // Parse input JSON into a JSONObject
        JSONObject inputObj = new JSONObject(inputJson);
        JSONObject resultObj = inputObj.getJSONObject("result");

        // Extract the three nested arrays
        JSONArray accountNamesArray = resultObj.getJSONArray("accountnames");
        JSONArray salesArray = resultObj.getJSONArray("sales");
        JSONArray countResultArray = resultObj.getJSONArray("countResult");

        // Map to hold grouped account data (key: accountId, value: unified account object)
        Map<Integer, JSONObject> accountMap = new HashMap<>();

        // Populate account names first
        for (int i = 0; i < accountNamesArray.length(); i++) {
            JSONObject account = accountNamesArray.getJSONObject(i);
            int accountId = account.getInt("accountId");
            JSONObject accountEntry = new JSONObject();
            accountEntry.put("accountId", accountId);
            accountEntry.put("accountName", account.getString("accountName"));
            accountMap.put(accountId, accountEntry);
        }

        // Add sales data to existing or new account entries
        for (int i = 0; i < salesArray.length(); i++) {
            JSONObject sale = salesArray.getJSONObject(i);
            int accountId = sale.getInt("accountId");
            JSONObject accountEntry = accountMap.getOrDefault(accountId, new JSONObject());
            accountEntry.put("accountId", accountId); // Ensure ID is present even for new entries
            accountEntry.put("accountSales", sale.getString("accountSales"));
            accountMap.put(accountId, accountEntry);
        }

        // Add count result data to existing or new account entries
        for (int i = 0; i < countResultArray.length(); i++) {
            JSONObject countResult = countResultArray.getJSONObject(i);
            int accountId = countResult.getInt("accountId");
            JSONObject accountEntry = accountMap.getOrDefault(accountId, new JSONObject());
            accountEntry.put("accountId", accountId);
            accountEntry.put("accountResult", countResult.getString("accountResult"));
            accountMap.put(accountId, accountEntry);
        }

        // Convert the map values into a JSON array for the final result
        JSONArray finalArray = new JSONArray(accountMap.values());
        JSONObject finalResult = new JSONObject();
        finalResult.put("unifiedAccounts", finalArray);

        // Print the pretty-formatted final result
        System.out.println(finalResult.toString(4));
    }
}

Key Details

  • Grouping Logic: The accountMap ensures we only have one entry per unique accountId, avoiding duplicates.
  • Handling Missing Data: Using getOrDefault means accounts that only appear in one array are still included in the final output with their available fields.
  • Clean Output: The final unifiedAccounts array gives you a single source of truth for each account's data.

Sample Final Output

{
    "unifiedAccounts": [
        {
            "accountId": 878487,
            "accountName": "ravi",
            "accountSales": "98"
        },
        {
            "accountId": 878488,
            "accountName": "Hari",
            "accountSales": "89",
            "accountResult": "945"
        },
        {
            "accountId": 878489,
            "accountResult": "9452"
        }
    ]
}

If you prefer using Jackson (another popular JSON library) instead of org.json, the approach is similar—you'd use a Map<Integer, YourAccountPOJO> to group data, then serialize it back to JSON. Just let me know if you want that version!

内容的提问来源于stack exchange,提问作者hari adabala

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:03:49