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

我必须在 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 {}


解决问题的最佳方法是什么?


萧十郎
浏览 155回答 1
1回答

墨色风雨

我通过更改解决了它: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])    }}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go