在 Java 中处理 JSON 去除空 children数组,可以使用 Jackson 库。这里有几种实现方式

在 Java 中处理 JSON 去除空 children数组,可以使用 Jackson 库。这里有几种实现方式:

方法1:使用 Jackson 递归处理

复制代码
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class JsonCleaner {
    
    public static JsonNode removeEmptyChildren(JsonNode node) {
        if (node.isObject()) {
            ObjectNode objectNode = (ObjectNode) node;
            
            // 遍历对象的所有字段
            java.util.Iterator<java.util.Map.Entry<String, JsonNode>> fields = objectNode.fields();
            while (fields.hasNext()) {
                java.util.Map.Entry<String, JsonNode> entry = fields.next();
                String fieldName = entry.getKey();
                JsonNode fieldValue = entry.getValue();
                
                if ("children".equals(fieldName) && fieldValue.isArray() && fieldValue.isEmpty()) {
                    // 删除空的 children 数组
                    fields.remove();
                } else {
                    // 递归处理子节点
                    objectNode.set(fieldName, removeEmptyChildren(fieldValue));
                }
            }
        } else if (node.isArray()) {
            ArrayNode arrayNode = (ArrayNode) node;
            
            // 处理数组中的每个元素
            for (int i = 0; i < arrayNode.size(); i++) {
                arrayNode.set(i, removeEmptyChildren(arrayNode.get(i)));
            }
        }
        
        return node;
    }
    
    public static void main(String[] args) throws Exception {
        String json = """
            {
                "id": 1,
                "name": "root",
                "children": [
                    {
                        "id": 2,
                        "name": "child1",
                        "children": []
                    },
                    {
                        "id": 3,
                        "name": "child2",
                        "children": [
                            {
                                "id": 4,
                                "name": "grandchild",
                                "children": []
                            }
                        ]
                    }
                ]
            }
            """;
        
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(json);
        
        // 清理空 children
        JsonNode cleanedNode = removeEmptyChildren(rootNode);
        
        // 输出结果
        String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cleanedNode);
        System.out.println(result);
    }
}

方法2:使用 Map 和 List 处理(更简洁)

复制代码
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;

public class JsonCleaner2 {
    
    public static Object cleanEmptyChildren(Object obj) {
        if (obj instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) obj;
            Map<String, Object> result = new HashMap<>();
            
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                
                if ("children".equals(key) && value instanceof List && ((List<?>) value).isEmpty()) {
                    // 跳过空的 children
                    continue;
                }
                
                // 递归处理
                result.put(key, cleanEmptyChildren(value));
            }
            return result;
            
        } else if (obj instanceof List) {
            List<Object> list = (List<Object>) obj;
            List<Object> result = new ArrayList<>();
            
            for (Object item : list) {
                result.add(cleanEmptyChildren(item));
            }
            return result;
        }
        
        return obj; // 基本类型直接返回
    }
    
    public static void main(String[] args) throws Exception {
        String json = """
            {
                "id": 1,
                "name": "root",
                "children": [
                    {
                        "id": 2,
                        "name": "child1",
                        "children": []
                    },
                    {
                        "id": 3,
                        "name": "child2",
                        "children": [
                            {
                                "id": 4,
                                "name": "grandchild",
                                "children": []
                            }
                        ]
                    }
                ]
            }
            """;
        
        ObjectMapper mapper = new ObjectMapper();
        
        // 读取为 Map
        TypeReference<Map<String, Object>> typeRef = new TypeReference<>() {};
        Map<String, Object> data = mapper.readValue(json, typeRef);
        
        // 清理空 children
        Object cleaned = cleanEmptyChildren(data);
        
        // 输出结果
        String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cleaned);
        System.out.println(result);
    }
}

方法3:使用 Gson 库

如果你使用 Gson 库,可以这样实现:

复制代码
import com.google.gson.*;
import java.util.Map;
import java.util.HashMap;

public class GsonJsonCleaner {
    
    public static JsonElement cleanEmptyChildren(JsonElement element) {
        if (element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();
            JsonObject newObject = new JsonObject();
            
            for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                String key = entry.getKey();
                JsonElement value = entry.getValue();
                
                if ("children".equals(key) && value.isJsonArray() && value.getAsJsonArray().size() == 0) {
                    // 跳过空的 children
                    continue;
                }
                
                newObject.add(key, cleanEmptyChildren(value));
            }
            return newObject;
            
        } else if (element.isJsonArray()) {
            JsonArray jsonArray = element.getAsJsonArray();
            JsonArray newArray = new JsonArray();
            
            for (JsonElement item : jsonArray) {
                newArray.add(cleanEmptyChildren(item));
            }
            return newArray;
        }
        
        return element; // 基本类型
    }
    
    public static void main(String[] args) {
        String json = """
            {
                "id": 1,
                "name": "root",
                "children": [
                    {
                        "id": 2,
                        "name": "child1",
                        "children": []
                    }
                ]
            }
            """;
        
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonElement jsonElement = JsonParser.parseString(json);
        
        // 清理空 children
        JsonElement cleaned = cleanEmptyChildren(jsonElement);
        
        // 输出结果
        System.out.println(gson.toJson(cleaned));
    }
}

依赖配置(Maven)

Jackson:

复制代码
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

Gson:

复制代码
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>

输出结果

所有方法都会输出相同的结果(空的 children数组被移除):

复制代码
{
  "id": 1,
  "name": "root",
  "children": [
    {
      "id": 3,
      "name": "child2",
      "children": [
        {
          "id": 4,
          "name": "grandchild"
        }
      ]
    }
  ]
}

扩展功能

如果你希望保留 children属性但设置为 null,可以修改清理逻辑:

复制代码
// 在方法2的基础上修改
if ("children".equals(key) && value instanceof List && ((List<?>) value).isEmpty()) {
    // 设置为 null
    result.put(key, null);
    continue;
}

或者完全删除该属性(如上面的示例所示)。

选择哪种方法取决于你项目中使用的 JSON 库:

  • 如果使用 Jackson,推荐方法1或方法2

  • 如果使用 Gson,使用方法3

  • 方法2(使用 Map/List)代码更简洁,容易理解

相关推荐
计算机安禾3 小时前
【数据结构与算法】第33篇:交换排序(二):快速排序
c语言·开发语言·数据结构·数据库·算法·矩阵·排序算法
William Dawson3 小时前
Java 后端高频 20 题超详细解析 ①
java·开发语言
lly2024063 小时前
PHP 魔术常量
开发语言
Evand J3 小时前
【MATLAB例程分享】三维非线性目标跟踪,观测为:距离+方位角+俯仰角,使用无迹卡尔曼滤波(UKF)与RTS平滑,高精度定位
开发语言·matlab·目标跟踪
编程之升级打怪3 小时前
Java NIO的简单封装
java·开发语言·nio
Chase_______4 小时前
【Python基础 | 第5章】面向对象与异常处理:一文搞懂类、对象、封装、继承、多态
开发语言·python
啦啦啦!4 小时前
项目环境的搭建,项目的初步使用和deepseek的初步认识
开发语言·c++·人工智能·算法
YanDDDeat4 小时前
【大模型微调】基于 Llama3-8B 的 LoRA 微调专有领域QA 问答对生成模型
python·语言模型·llama
小李云雾4 小时前
Python Web 路由详解:核心知识点全覆盖
开发语言·前端·python·路由