From a7f30d1640cbfb5452f10076e525a9c3b88f3941 Mon Sep 17 00:00:00 2001 From: qhd <1766646056@qq.com> Date: Wed, 8 Jul 2026 13:37:09 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=94=AF=E6=8C=81=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=8D=95=E4=B8=AAJSON=E5=AF=B9=E8=B1=A1=E4=B8=BA=E5=8D=95?= =?UTF-8?q?=E5=85=83=E7=B4=A0=E6=95=B0=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/util/mapping.go | 37 +++++++++++++++++++++++++++++-------- 1 file changed, 29 insertions(+), 8 deletions(-) diff --git a/common/util/mapping.go b/common/util/mapping.go index 715334a..00e2856 100644 --- a/common/util/mapping.go +++ b/common/util/mapping.go @@ -33,24 +33,45 @@ func ParseAndValidate(raw map[string]any, requiredFields []string) (map[string]a return r }, contentStr) - var arr []any - if err := json.Unmarshal([]byte(contentStr), &arr); err != nil { + // 第一步:先解析为通用 interface{},判断是对象还是数组 + var data any + if err := json.Unmarshal([]byte(contentStr), &data); err != nil { return raw, fmt.Errorf("JSON解析失败: %w", err) } - if len(arr) == 0 { - return raw, fmt.Errorf("解析后数组为空") + + var arr []any + switch val := data.(type) { + case []any: + // 本身就是数组,直接赋值 + arr = val + case map[string]any: + // 单个对象,包装成单元素数组,统一后续逻辑 + arr = []any{val} + default: + return raw, fmt.Errorf("不支持的JSON类型,仅允许对象/数组") } + if len(arr) == 0 { + return raw, fmt.Errorf("解析后数据数组为空") + } + + // 校验每一项的必填字段 for _, field := range requiredFields { - for i, r := range arr { - round, _ := r.(map[string]any) - if round != nil && gjson.New(round).Get(field).IsNil() { + for i, item := range arr { + itemMap, ok := item.(map[string]any) + if !ok { + return raw, fmt.Errorf("rounds[%d] 不是合法JSON对象", i) + } + if gjson.New(itemMap).Get(field).IsNil() { return raw, fmt.Errorf("rounds[%d] 缺少必填字段: %s", i, field) } } } - return map[string]any{"total_rounds": len(arr), "rounds": arr}, nil + return map[string]any{ + "total_rounds": len(arr), + "rounds": arr, + }, nil } // ParseStructResult 解析结构结果