如何通过使用Java映射AccountID来掩盖Jonobject到另一个必需的JSONOBECT



**我的jsonobject的结果以下转换为以下bellow代码,并搜索了许多这样的使用Java转换的方法,但是我将其转换为**

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

*,这是要转换的示例代码 *

{
    "result": [{
            "accountName": "Hari",
            "accountSales": "89",
            "accountResult": "945",
            "accountId": 878488
        },
        {
            "accountName": "ravi",
            "accountSales": "98",
            "accountId": 878487
        },
        {
            "accountResult": "9452",
            "accountId": 878489
        }
    ]
}
My required JSON data has to be formatted as below 

您需要按accountId对所有元素进行分组。您可以根据所使用的JSON库使用类似的内容。

初始化JSON对象:

JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");

创建一个地图以通过accountId

保存对象
Map<String, JSONObject> accountIds = new HashMap<>();

然后迭代JSON中的每个键,然后针对数组中的每个元素,然后迭代JSON中的对象的每个属性:

Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
    String key = (String) mainKeys.next();
    JSONArray array = resultJson.getJSONArray(key);
    for (int index = 0; index < array.length(); index++) {
        JSONObject object = array.getJSONObject(index);
        if (object.has("accountId")) {
            String accountId = object.get("accountId").toString();
            JSONObject accum = accountIds
                    .computeIfAbsent(accountId, (k) -> new JSONObject());
            // depending on the json impl you can use putAll or similar
            Iterator objKeys = object.keys();
            while (objKeys.hasNext()) {
                String property = (String) objKeys.next();
                accum.put(property, object.get(property));
            }
        } else {
            // does not have account id, ignore or throw
        }
    }
}

最终创建JSON文件,然后将元素添加到JSONArray

JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());

(注意:JSON在销售数组accountName而不是accountSales (

中有错误

最新更新