问题
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:
This seems to work:
Playground
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)
}
来源:https://stackoverflow.com/questions/39058902/json-decode-into-struct-as-interface-yields-mapstringinterface-not-struct