英文:
JSON decode into struct as interface{} yields map[string]interface{}, not struct
问题
这里有一个复制了问题的 Go Playground:
https://play.golang.org/p/GgHsLffp1G
基本上,我正在尝试编写一个函数,该函数接受一个结构体,并返回一个可以将 HTTP 请求解码为该类型的函数。不幸的是,一些类型信息丢失了,返回的类型是 map[string]interface{} 而不是正确的结构体类型。我该如何向 JSON 解码器传递正确的类型?JSON unmarshal 是否会更好地工作?
英文:
Here is a go playground replicating the issue:
https://play.golang.org/p/GgHsLffp1G
Basically, I'm trying to write a function that takes a struct and returns a function that can decode http requests as that type. Unfortunately some type information is being lost and the type being returned is a map[string]interface{} and not the correct struct type. How can I communicate the correct type to the JSON decoder? Would JSON unmarshal work better?
答案1
得分: 1
这似乎有效:
func requestParser(i interface{}) parser {
return func(r io.Reader) (interface{}, error) {
json.NewDecoder(r).Decode(i)
return reflect.ValueOf(i).Elem(), nil
}
}
func main() {
var foo Foo
s := "{\"Name\":\"Logan\"}"
p := requestParser(&foo)
}
英文:
This seems to work:
func requestParser(i interface{}) parser {
return func(r io.Reader) (interface{}, error) {
json.NewDecoder(r).Decode(i)
return reflect.ValueOf(i).Elem(), nil
}
}
func main() {
var foo Foo
s := "{\"Name\":\"Logan\"}"
p := requestParser(&foo)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论