From 0cdd9d4d9413ecdabb1d4c28f2c12f6e73bd16b0 Mon Sep 17 00:00:00 2001 From: NiuZiYuan Date: Thu, 22 May 2025 13:14:05 +0800 Subject: [PATCH] dev --- .../common/api/input/BaseInputModel.java | 41 +++++++++++++------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/syjiaer/clinic/server/common/api/input/BaseInputModel.java b/src/main/java/com/syjiaer/clinic/server/common/api/input/BaseInputModel.java index e0eb442..2c9a63f 100644 --- a/src/main/java/com/syjiaer/clinic/server/common/api/input/BaseInputModel.java +++ b/src/main/java/com/syjiaer/clinic/server/common/api/input/BaseInputModel.java @@ -5,38 +5,54 @@ import com.syjiaer.clinic.server.common.api.annotations.IMField; import com.syjiaer.clinic.server.common.exception.MessageException; import java.lang.reflect.Field; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; public abstract class BaseInputModel { public Map buildToMap() { Map map = new HashMap<>(); - // 遍历所有字段(包含父类) Class clazz = this.getClass(); while (clazz != null) { for (Field field : clazz.getDeclaredFields()) { field.setAccessible(true); try { - Object value = field.get(this); // 检查RequiredField注解 + Object value = field.get(this); String mapKey = null; if (field.isAnnotationPresent(IMField.class)) { - IMField annotation = field.getAnnotation(IMField.class); mapKey = annotation.key(); - if (annotation.required()) { - if (value == null || value.toString().isEmpty()) { - throw new MessageException("[" + annotation.key() + ":"+annotation.name()+"]不能为空"); - } + + if (annotation.required() && (value == null || (value instanceof String && ((String) value).isEmpty()))) { + throw new MessageException("[" + annotation.key() + ":" + annotation.name() + "] 不能为空"); } - } - if (value != null && mapKey != null && !value.toString().isEmpty()){ - map.put(mapKey, field.get(this)); + if (mapKey != null) { + // 处理 BaseInputModel 子类 + if (value instanceof BaseInputModel) { + map.put(mapKey, ((BaseInputModel) value).buildToMap()); + } + // 处理 List + else if (value instanceof List) { + List list = (List) value; + List> mappedList = new ArrayList<>(); + for (Object item : list) { + if (item instanceof BaseInputModel) { + mappedList.add(((BaseInputModel) item).buildToMap()); + } else { + mappedList.add((Map) item); // 假设基本类型已为 Map + } + } + map.put(mapKey, mappedList); + } + // 其他非空值直接放入 + else if (value != null && !(value instanceof String || value.toString().isEmpty())) { + map.put(mapKey, value); + } } - - } catch (IllegalAccessException e) { throw new RuntimeException(e); } @@ -45,4 +61,5 @@ public abstract class BaseInputModel { } return map; } + }