在Unmarshalling JSON时,我一直在努力找出为map[string]struct
类型调用外部结构的正确方法。
当代码全部在同一个包中时,代码可以工作,但是如果它是拉出导出的类型,那么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
中,而是将加载默认的struct值。我必须使用本地包结构来正确地解组值。
我道歉,上面的代码工作,事实证明它是一个流氓func (e *Bird) UnmarshalJSON(b []byte) error {}
的一部分,我浪费了这么多时间:(