我一直在努力找出map[string]struct
在解组 JSON 时调用外部结构的正确方法。
代码在同一个包中时有效,但是如果它正在提取导出的类型,则 Unmarshal 函数似乎存在错误。
package animals
type Bird struct {
Name string `json:"name"`
Description string `json:"description"`
}
package main
import (
"encoding/json"
"fmt"
"../animal"
)
func main() {
birdJson := `{"birds":{"name":"eagle","description":"bird of prey"}}`
var result map[string]animals.Bird //If Bird is external (animals.Bird) then the Unmarshal breaks
json.Unmarshal([]byte(birdJson), &result)
birds := result["birds"]
fmt.Printf("%s: %s", birds.Name, birds.Description)
// These entries will be the struct defaults instead of the values in birdJson
}
https://play.golang.org/p/e4FGIFath4s
所以上面的代码工作正常,但如果type Bird struct{}
是从另一个包导入的,那么当我设置map[string]animals.Bird
json.Unmarshal 时不起作用。
我发现的解决方法是设置一个新类型,如下所示:
type Bird animals.Bird
. 有没有更优雅的方式来做到这一点?
animal.Bird struct
如果将来的函数需要原始函数并且在尝试使用我的新本地类型时会出错,这将成为一个更大的问题。
更新:
我已经更新了上面的代码以显示非工作示例。问题是值不会正确加载到map[string]animals.Bird
默认结构值中。我必须使用本地包结构来正确解组这些值。