在 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)代码更简洁,容易理解