":{"message":"json: cannot unmarshal string into Go struct field ***.***.***.Cod...
🚨 错误信息
Credentials validation failed with status code 500 and response body {"error":{"message":"json: cannot unmarshal string into Go struct field ***.***.***.Code of type int","type":"rix_api_error","param":"","code":"bad_response_body"}}
🤖 AI解决方案
错误翻译
原文:json: cannot unmarshal string into Go struct field ..*.Code of type int
译文:JSON:无法将字符串反序列化为 Go 结构体字段 ..*.Code(期望类型为 int)
原因分析
这是一个 JSON 反序列化类型不匹配错误。API 响应中某个字段在代码中定义为整数类型,但实际接收到的是字符串类型的数据。
..*.Code 字段在结构体中定义为 int,但 API 返回的是字符串格式解决方案
方案1:修改 Go 结构体定义(推荐)
``
go
type YourStruct struct {
// 将 int 改为 string 或使用 json.Number
Code string json:"code"
// 或者使用更灵活的类型
// Code json.Number json:"code"
}
方案2:使用自定义 UnmarshalJSON 方法
go
type YourStruct struct {
Code int json:"code"
}func (s *YourStruct) UnmarshalJSON(data []byte) error {
type Alias YourStruct
aux := &struct {
Code interface{}
json:"code"
*Alias
}{
Alias: (*Alias)(s),
}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
switch v := aux.Code.(type) {
case float64:
s.Code = int(v)
case string:
if num, err := strconv.Atoi(v); err == nil {
s.Code = num
} else {
return fmt.Errorf("invalid code format: %s", v)
}
default:
return fmt.Errorf("unexpected type for code: %T", v)
}
return nil
}
``️ 预防措施
建议:与 API 提供方沟通,统一响应字段的数据类型标准。