为了账号安全,请及时绑定邮箱和手机立即绑定

在这种情况下如何解组 json?

在这种情况下如何解组 json?

Go
萧十郎 2023-02-28 20:22:42
我必须在 ELK 的 echo 框架中间件中解组 Json(请求,响应主体),就像这段代码一样。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)}这是工作,但是,某些 URI 响应[]map[string]interface{}类型。所以我得到了这个错误。json: cannot unmarshal array into Go value of type map[string]interface {}解决问题的最佳方法是什么?
查看完整描述

1 回答

?
墨色风雨

TA贡献1853条经验 获得超6个赞

我通过更改解决了它:


var reqJSONBody, resJSONBody interface{}

if len(*reqBody) > 0 {

    if err := json.Unmarshal(*reqBody, &reqJSONBody); err != nil {

        gl.ServiceLogger.Error("error parsing the request body: ", requestURI, err)

    }

    encryptPrivacyField(&reqJSONBody)

}

所以我必须encryptPrivacyField像这样改变方法:


func encryptPrivacyField(data *interface{}) {

switch reflect.TypeOf(*data).Kind() {

case reflect.Map:

    for _, field := range getPrivacyFieldList() {

        if item, ok := (*data).(map[string]interface{})[field]; ok && item != nil {

            (*data).(map[string]interface{})[field] = db.NewEncString(fmt.Sprintf("%v", (*data).(map[string]interface{})[field]))

        }

    }


    for _, field := range getHashFieldList() {

        if item, ok := (*data).(map[string]interface{})[field]; ok && item != nil {

            (*data).(map[string]interface{})[field] = db.NewHashString(fmt.Sprintf("%v", (*data).(map[string]interface{})[field]))

        }

    }

case reflect.Slice:

    for index, _ := range (*data).([]interface{}) {

        encryptPrivacyField(&(*data).([]interface{})[index])

    }


}

}


查看完整回答
反对 回复 2023-02-28
  • 1 回答
  • 0 关注
  • 154 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号