获取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解决方案
错误翻译
原文:json: cannot unmarshal object into Go struct field .promptFeedback of type []struct { BlockReason string "json:\"blockReason\"" }
译文:json: 无法将对象反序列化为 Go 结构体字段 .promptFeedback,期望类型是 []struct { BlockReason string "json:\"blockReason\"" }
原因分析
- 根本原因:Go语言的JSON反序列化类型不匹配
- 具体问题:API返回的
promptFeedback字段是一个对象(object),但代码中期望的是数组(slice)类型 - 错误位置:在解析AI API响应时,结构体字段类型定义错误
解决方案
// 修复后的结构体定义
type APIResponse struct {
Candidates []Candidate `json:"candidates"`
PromptFeedback PromptFeedback `json:"promptFeedback"` // 从数组改为对象
UsageMetadata UsageMetadata `json:"usageMetadata"`
}
type PromptFeedback struct {
SafetyRatings []SafetyRating `json:"safetyRatings"`
// 其他可能的字段...
}
// 或者如果不需要promptFeedback,可以忽略该字段
type APIResponse struct {
Candidates []Candidate `json:"candidates"`
PromptFeedback interface{} `json:"promptFeedback"` // 使用interface{}忽略
UsageMetadata UsageMetadata `json:"usageMetadata"`
}
预防措施
omitempty标签,避免未知字段导致的解析错误type PromptFeedback struct {
SafetyRatings []SafetyRating `json:"safetyRatings,omitempty"`
}