":{"message":"json: cannot unmarshal string into Go struct field ***.***.***.Cod...

2025年11月26日 13:55 状态: processing

🚨 错误信息

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 响应中某个字段在代码中定义为整数类型,但实际接收到的是字符串类型的数据。

  • 根本原因:结构体字段类型定义与 JSON 响应数据类型不一致
  • 错误位置:Go 代码中处理 API 响应的反序列化逻辑
  • 具体问题..*.Code 字段在结构体中定义为 int,但 API 返回的是字符串格式
  • 解决方案

    方案1:修改 Go 结构体定义(推荐)

    type YourStruct struct {
        // 将 int 改为 string 或使用 json.Number
        Code string `json:"code"`
        // 或者使用更灵活的类型
        // Code json.Number `json:"code"`
    }

    方案2:使用自定义 UnmarshalJSON 方法

    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 文档一致性检查:确保 API 文档中的数据类型与实际实现一致

  • 使用接口测试工具:在开发阶段使用 Postman 或类似工具验证 API 响应格式

  • 添加类型验证:在反序列化前添加数据类型验证逻辑,提高代码健壮性

建议:与 API 提供方沟通,统一响应字段的数据类型标准。