我正在为Golang开发Telegram Bot API包装器(我知道已经有一些包装了,但是我正在做这个学习)。我有一个响应结构:
type Response struct {
Ok bool `json:"ok"`
ErrorCode int64 `json:"error_code"`
Description string `json:"description"`
Result interface{} `json:"result"`
}
我不知道
Result
的实际类型:电报服务器可以返回很多信息。我为每个构建了一个结构,但是我不知道Result
中将包含哪个结构。当
Unmarshal
将HTTP响应中的JSON转换为Response
结构时,除Result
之外的所有内容均已正确加载。在我确定Result将是
User
(例如)的函数中,我正在执行user := resp.Result.(*User)
,但是在运行时出现以下错误:panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User
。因此,Result
是map[string]interface{}
。如何将其转换为*User
?感谢您的回答。
最佳答案
确定它是什么类型后,将其设置为json.RawMessage
并在第二步中将其解码。
看一看https://golang.org/pkg/encoding/json/#RawMessage的示例。