json.Unmarshal 没有正确解码到内部接口{}
json.Unmarshal not decoding into inner interface{} correctly
我正在为 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
的实际类型:Telegram服务器可以返回很多;我为每一个都做了一个结构,但我不知道哪个会在 Result
中。
当 Unmarshal
将来自 HTTP 响应的 JSON 发送到 Response
结构时,除了 Result
.
之外的所有内容都被正确加载
在我确定结果将是 User
的函数中(例如),我正在执行 user := resp.Result.(*User)
,但在运行时出现以下错误 :
panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User
。所以,Result
是一个 map[string]interface{}
。如何将其转换为 *User
?
感谢您的回答。
将其设为 json.RawMessage
并在确定其类型后在第二步中解组。
我正在为 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
的实际类型:Telegram服务器可以返回很多;我为每一个都做了一个结构,但我不知道哪个会在 Result
中。
当 Unmarshal
将来自 HTTP 响应的 JSON 发送到 Response
结构时,除了 Result
.
在我确定结果将是 User
的函数中(例如),我正在执行 user := resp.Result.(*User)
,但在运行时出现以下错误 :
panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User
。所以,Result
是一个 map[string]interface{}
。如何将其转换为 *User
?
感谢您的回答。
将其设为 json.RawMessage
并在确定其类型后在第二步中解组。