如何为嵌套子数组添加type字段仅为VALUE的校验规则
嵌套节点Type值校验方案
核心思路
由于你的数据是多层嵌套的树形结构,必须遍历所有层级的节点(包括所有children子数组中的节点),逐个校验type字段是否严格等于VALUE,不符合则抛出异常。下面提供两种实现方式:递归遍历和非递归遍历(避免栈溢出风险)。
1. 定义实体类(以Java为例)
首先需要将JSON转换为对应的实体对象,确保能获取到type和children字段:
import java.util.List; public class HierarchyNode { // 对应JSON中的所有字段,这里仅保留核心校验所需字段 private String id; private String type; private List<HierarchyNode> children; // 必须提供getter方法,用于校验逻辑 public String getId() { return id; } public String getType() { return type; } public List<HierarchyNode> getChildren() { return children; } // 其他字段的getter/setter根据实际需求补充 }
2. 递归校验实现
适合层级较浅的结构,代码简洁直观:
public class NodeValidator { // 允许的唯一type值 private static final String VALID_TYPE = "VALUE"; public static void validateAllNodes(List<HierarchyNode> nodeList) { if (nodeList == null || nodeList.isEmpty()) { return; } for (HierarchyNode node : nodeList) { // 校验当前节点的type if (!VALID_TYPE.equals(node.getType())) { throw new IllegalArgumentException( String.format("节点ID[%s]的type非法:仅允许'%s',当前值为'%s'", node.getId(), VALID_TYPE, node.getType()) ); } // 递归校验子节点 validateAllNodes(node.getChildren()); } } }
3. 非递归校验实现(推荐层级较深的场景)
使用队列迭代遍历,避免递归栈溢出问题:
import java.util.LinkedList; import java.util.List; import java.util.Queue; public class NodeValidator { private static final String VALID_TYPE = "VALUE"; public static void validateAllNodesNonRecursive(List<HierarchyNode> nodeList) { if (nodeList == null || nodeList.isEmpty()) { return; } Queue<HierarchyNode> nodeQueue = new LinkedList<>(nodeList); while (!nodeQueue.isEmpty()) { HierarchyNode currentNode = nodeQueue.poll(); // 校验当前节点type if (!VALID_TYPE.equals(currentNode.getType())) { throw new IllegalArgumentException( String.format("节点ID[%s]的type非法:仅允许'%s',当前值为'%s'", currentNode.getId(), VALID_TYPE, currentNode.getType()) ); } // 将子节点加入队列,继续校验 if (currentNode.getChildren() != null && !currentNode.getChildren().isEmpty()) { nodeQueue.addAll(currentNode.getChildren()); } } } }
使用方式
将JSON转换为List<HierarchyNode>后,直接调用校验方法即可:
// 假设你已经将JSON转换为List<HierarchyNode> List<HierarchyNode> nodeList = convertJsonToHierarchyNodeList(jsonStr); // 执行校验,不符合则抛出IllegalArgumentException NodeValidator.validateAllNodes(nodeList);
注意事项
- 如果需要忽略大小写校验(比如允许
value或Value),将VALID_TYPE.equals(node.getType())改为VALID_TYPE.equalsIgnoreCase(node.getType())。 - 必须处理
children为null的情况,避免空指针异常。
内容的提问来源于stack exchange,提问作者Rajesh
相关产品推荐
相关产品推荐

