获取AI决策失败: 调用AI API失败: 解析响应失败: json: cannot unmarshal object into Go struct field...
🚨 错误信息
获取AI决策失败: 调用AI API失败: 解析响应失败: json: cannot unmarshal object into Go struct field .promptFeedback of type []struct { BlockReason string "json:\"blockReason\"" }
响应内容: {"candidates":[{"content":{"role":"model","parts":null},"finishReason":"MAX_TOKENS","index":0,"safetyRatings":null}],"promptFeedback":{"safetyRatings":null},"usageMetadata":{"promptTokenCount":11875,"candidatesTokenCount":0,"totalTokenCount":13874,"thoughtsTokenCount":1999,"promptTokensDetails":[{"modality":"TEXT","tokenCount":11875}]}}
🤖 AI解决方案
错误翻译
根本原因:Go语言的JSON反序列化类型不匹配
具体问题:API返回的
错误位置:在解析AI API响应时,结构体字段类型定义错误 API文档对齐:确保Go结构体定义与AI服务提供商的最新API文档完全匹配
使用JSON标签:为所有结构体字段添加omitempty
`
原文:json: cannot unmarshal object into Go struct field .promptFeedback of type []struct { BlockReason string "json:\"blockReason\"" }
译文:json: 无法将对象反序列化为 Go 结构体字段 .promptFeedback,期望类型是 []struct { BlockReason string "json:\"blockReason\"" }
原因分析
promptFeedback字段是一个对象(object),但代码中期望的是数组(slice)类型解决方案
``gojson:"candidates"
// 修复后的结构体定义
type APIResponse struct {
Candidates []Candidate json:"promptFeedback"
PromptFeedback PromptFeedback // 从数组改为对象json:"usageMetadata"
UsageMetadata UsageMetadata
}
type PromptFeedback struct {
SafetyRatings []SafetyRating json:"safetyRatings"
// 其他可能的字段...
}
// 或者如果不需要promptFeedback,可以忽略该字段
type APIResponse struct {
Candidates []Candidate json:"candidates"json:"promptFeedback"
PromptFeedback interface{} // 使用interface{}忽略json:"usageMetadata"
UsageMetadata UsageMetadata `
}
预防措施
标签,避免未知字段导致的解析错误`
go
type PromptFeedback struct {
SafetyRatings []SafetyRating json:"safetyRatings,omitempty"
}
``