当前位置: 首页 > 图灵资讯 > 技术篇> 从Java中的JSONArray集合中提取键值对并合并为一个JSONArray

从Java中的JSONArray集合中提取键值对并合并为一个JSONArray

来源:图灵教育
时间:2025-09-09 17:23:26

从java中的jsonarray集合中提取键值对并合并为一个jsonarray

本文将详细介绍如何使用Java代码合并两个JSONAray中的数据,并生成一个新的JSONAray。假设我们有两个JSONAray,它们之间有一个公共键(例如 "id“)相关性。我们的目标是根据这个关联键合并JSONAray中的两个JSONObject,最终得到一个新的JSONAray,包括合并后的键值对。

首先,我们需要明确JSONAray和JSONObject的概念。JSONAray可以看作是JSONObject的数组,而JSONObject是键值对的集合。

实现步骤

  1. 准备数据: 首先,你需要准备两个JSONAray。假设第一个JSONAray包括 "name" 和 "id" 第二个JSONAray包含字段 "color"、"id" 和 "country" 字段。

    立即学习“Java免费学习笔记(深入);

    import org.json.JSONArray;
    import org.json.JSONObject;
    
    public class JSONArrayMerger {
    
        public static void main(String[] args) {
            JSONArray array1 = new JSONArray();
            array1.put(new JSONObject().put("name", "John").put("id", "1"));
            array1.put(new JSONObject().put("name", "Adam").put("id", "2"));
    
            JSONArray array2 = new JSONArray();
            array2.put(new JSONObject().put("color", "red").put("id", "1").put("country", "Poland"));
            array2.put(new JSONObject().put("color", "green").put("id", "2").put("country", "Germany"));
            array2.put(new JSONObject().put("color", "red").put("id", "3").put("country", "England"));
    
            JSONArray mergedArray = mergeJSONArrays(new JSONArray[]{array1, aray2}, "id");
    
            System.out.println(mergedArray.toString(2)); // 使用tostring(2)格式输出,方便阅读
        }

  2. 合并方法的创建: 创建一种接收两个JSONAray和一个关联键作为参数的方法。该方法将返回合并后的JSONAray。

        public static JSONArray mergeJSONArrays(JSONArray[] arraysToMerge, String key) {
            Map<String, JSONObject> merged = new HashMap<>();
            for (JSONArray array : arraysToMerge) {
                for (int i = 0; i < array.length(); i++) {
                    JSONObject obj = array.optJSONObject(i);
                    if (obj != null) {
                        String id = obj.optString(key);
                        if (id != null) {
                            JSONObject existingObj = merged.computeIfAbsent(id, (k) -> {
                                obj.remove(key);
                                return obj;
                            });
                            for (String name : JSONObject.getNames(obj)) {
                                if (!name.equals(key)) {
                                    try {
                                        existingObj.put(name, obj.get(name));
                                    } catch (JSONException e) {
                                        // 处理JSONException,例如,打印错误的信息
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return new JSONArray(merged.values());
        }

  3. JSONAraray合并JSONObjecttect: 在合并方法中,首先创建一个 HashMap 用于存储合并后的JSONObject。键是关联键的值,值是合并后的JSONObject。然后,通过每个JSONAray,为每个JSONObject提取关联键的值。如果该值已经存在 HashMap 在中间,将当前JSONObject的键值添加到现有的JSONObject中。否则,创建新的JSONObject,将当前JSONObject的键值添加到新的JSONObject中,并添加新的JSONObject HashMap 中。

  4. JSONAray创造了新的创造: 最后,将 HashMap JSONObject全部转换为JSONAray,并返回JSONAray。

完整的代码示例

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

import java.util.HashMap;
import java.util.Map;

public class JSONArrayMerger {

    public static void main(String[] args) {
        JSONArray array1 = new JSONArray();
        try {
            array1.put(new JSONObject().put("name", "John").put("id", "1"));
            array1.put(new JSONObject().put("name", "Adam").put("id", "2"));

            JSONArray array2 = new JSONArray();
            array2.put(new JSONObject().put("color", "red").put("id", "1").put("country", "Poland"));
            array2.put(new JSONObject().put("color", "green").put("id", "2").put("country", "Germany"));
            array2.put(new JSONObject().put("color", "red").put("id", "3").put("country", "England"));

            JSONArray mergedArray = mergeJSONArrays(new JSONArray[]{array1, aray2}, "id");

            System.out.println(mergedArray.toString(2)); // 使用tostring(2)格式输出,方便阅读
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public static JSONArray mergeJSONArrays(JSONArray[] arraysToMerge, String key) {
        Map<String, JSONObject> merged = new HashMap<>();
        for (JSONArray array : arraysToMerge) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj = array.optJSONObject(i);
                if (obj != null) {
                    String id = obj.optString(key);
                    if (id != null) {
                        JSONObject existingObj = merged.computeIfAbsent(id, (k) -> {
                            obj.remove(key);
                            return obj;
                        });
                        for (String name : JSONObject.getNames(obj)) {
                            if (!name.equals(key)) {
                                try {
                                    existingObj.put(name, obj.get(name));
                                } catch (JSONException e) {
                                    // 处理JSONException,例如,打印错误的信息
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            }
        }
        return new JSONArray(merged.values());
    }
}

注意事项

  • JSON库: 使用了代码示例 org.json 图书馆。您需要确保该图书馆包含在您的项目中。您可以通过Maven或Gradle等构建工具添加依赖。
  • 键冲突: 如果两个JSONAray中有相同的键,那么后一个JSONAray中的值将覆盖前一个JSONAray中的值。 如果需要更复杂的冲突处理逻辑,则需要在代码中添加相应的逻辑。
  • 异常处理: 在实际应用中,您需要添加适当的异常处理代码,如处理 JSONException。

总结

本文介绍了如何使用Java代码合并两个JSONAray中的数据,并生成一个新的JSONAray。通过使用 HashMap 数据结构可以很容易地根据关联键合并JSONObject。该方法可应用于需要合并JSONAray数据的各种场景。请根据您的实际需要修改和扩展代码示例。

以上是从JavaJSONAray集合中提取的关键值对合并为JSONAray的详细内容。请关注图灵教育的其他相关文章!