json.Unmarshal无法正确解码为内部interface{}。

huangapple go评论89阅读模式
英文:

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 Unmarshaling 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.

huangapple
  • 本文由 发表于 2017年2月26日 01:49:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/42459498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定