英文:
json.Unmarshal not decoding into inner interface{} correctly
问题
我正在为Golang开发一个Telegram Bot API的包装器(我知道已经有一些了,但我这样做是为了学习)。我有一个Response结构体:
type Response struct {
Ok bool `json:"ok"`
ErrorCode int64 `json:"error_code"`
Description string `json:"description"`
Result interface{} `json:"result"`
}
我无法确定Result
的实际类型:Telegram服务器可能返回很多不同的类型;我为每个类型都创建了一个结构体,但我不知道Result
会是哪个类型。当我将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
类型?
谢谢任何回答。
英文:
I'm developing a Telegram Bot API wrapper for Golang (I know there are already some but I'm doing this for learning). I have a Response struct:
type Response struct {
Ok bool `json:"ok"`
ErrorCode int64 `json:"error_code"`
Description string `json:"description"`
Result interface{} `json:"result"`
}
I can't know the actual type of Result
: a lot can be returned by Telegram servers; I made a struct for each one, but I don't know which one will be in Result
.
When Unmarshal
ing a JSON from an HTTP response into the Response
struct, everything is loaded correctly, except Result
.
In a function where I am sure Result will be an User
(for example), I'm doing user := resp.Result.(*User)
, but I get the following error at runtime:
panic: interface conversion: interface {} is map[string]interface {}, not *tgbot.User
. So, Result
is a map[string]interface{}
. How can I transform it into a *User
?
Thanks for any answers.
答案1
得分: 6
将其转换为json.RawMessage
,并在第二步进行解组,当您确定其类型时。
请查看https://golang.org/pkg/encoding/json/#RawMessage上的示例。
英文:
Make it a json.RawMessage
and unmarshal it in a second step, when you're sure what type it is.
Take a look at the examples at https://golang.org/pkg/encoding/json/#RawMessage.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论