Echo框架中间件JSON反序列化报错:数组转map失败的解决方法
JSON反序列化数组到Map报错的最优解决方法
为满足ELK日志需求,我在Echo框架中间件中对请求、响应的JSON Body进行反序列化,原本代码可正常运行,但部分URI返回[]map[string]interface{}类型的JSON,触发错误:json: cannot unmarshal array into Go value of type map[string]interface {},原代码如下:
var reqJSONBody, resJSONBody map[string]interface{} if len(*reqBody) > 0 { if err := unmarshalJSON(reqBody, &reqJSONBody); err != nil { gl.ServiceLogger.Error("error parsing the request body: ", requestURI, err) } encryptPrivacyField(&reqJSONBody) } if len(*resBody) > 0 && resContentType != "" && strings.Contains(resContentType, "application/json") { if err := unmarshalJSON(resBody, &resJSONBody); err != nil { gl.ServiceLogger.Error("error parsing the response body: ", requestURI, err) } encryptPrivacyField(&resJSONBody) }
最优解决方法:动态适配JSON对象与数组类型
核心思路是先将JSON反序列化为interface{},再通过类型断言判断结构类型(对象/数组),递归处理隐私字段:
- 修改反序列化目标变量类型
将原来的map[string]interface{}改为interface{},兼容对象和数组两种格式:
var reqJSONBody interface{} if len(*reqBody) > 0 { if err := unmarshalJSON(reqBody, &reqJSONBody); err != nil { gl.ServiceLogger.Error("error parsing the request body: ", requestURI, err) } encryptPrivacyField(reqJSONBody) } var resJSONBody interface{} if len(*resBody) > 0 && resContentType != "" && strings.Contains(resContentType, "application/json") { if err := unmarshalJSON(resBody, &resJSONBody); err != nil { gl.ServiceLogger.Error("error parsing the response body: ", requestURI, err) } encryptPrivacyField(resJSONBody) }
- 重构
encryptPrivacyField函数,支持多类型处理
让函数能递归处理JSON对象和数组,以及嵌套的结构:
func encryptPrivacyField(data interface{}) { switch v := data.(type) { // 处理JSON对象(map结构) case map[string]interface{}: for key, val := range v { // 匹配隐私字段(根据实际业务调整字段列表) if key == "phone" || key == "idCard" || key == "password" { v[key] = "***" // 替换为加密逻辑或掩码 } else { // 递归处理嵌套的子结构 encryptPrivacyField(val) } } // 处理JSON数组(slice结构) case []interface{}: for _, item := range v { // 递归处理数组中的每个元素 encryptPrivacyField(item) } // 基础类型(字符串、数字等)无需处理,直接返回 default: return } }
方案优势
- 完全兼容JSON对象和数组两种格式,解决原有的反序列化报错问题
- 递归处理所有层级的嵌套结构,确保隐私字段不遗漏
- 保留原始JSON的结构完整性,不影响ELK日志的解析
内容的提问来源于stack exchange,提问作者BJKang
相关产品推荐
相关产品推荐

