在这种情况下如何反序列化 JSON 数据?

huangapple go评论75阅读模式
英文:

How to unmasrshal json in this case?

问题

我必须在echo框架的中间件中为ELK解析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 {}

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

英文:

I have to unmarshal Json(Request, Response Body) in echo framework midleware for ELK, like this code.

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)
}

And it is work,

But, Some URI response to []map[string]interface{} type.

So I got this error.

json: cannot unmarshal array into Go value of type map[string]interface {}

What is the best way to solve the problem?

答案1

得分: 0

我通过更改以下代码解决了这个问题:

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])
        }

    }
}

感谢@mkopriva的建议。

英文:

I solved it by changing:

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)
}

So I have to change encryptPrivacyField method like this:

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])
	}

}
}

Thanks to @mkopriva for the advice.

huangapple
  • 本文由 发表于 2022年10月13日 16:42:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/74052859.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定