JSON decode into struct as interface{} yields map[string]interface{}, not struct

耗尽温柔 提交于 2019-12-11 01:59:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!